var votedCheckBoxImage = `<img class="selected-poll-img" src="../assets/images/poll/selected-poll.png">`
$(document).ready(function(){

        $(document).on('click', '.one-option:not(".poll-votted-already")', function(){
            let postid = $(this).closest('.post').attr('data-post-id');
            let totalVotes = $(this).closest('.post').attr('data-total-votes');
            let optionId = $(this).attr('data-option-id');
            chrome.storage.local.get(['login'], function(st){
                if(st.login === undefined || !st.login || st.login == '' ){
                    $('.login-link').click()
                }else{
                    if(totalVotes == 0){
                        totalVotes = 1
                    }else{
                         totalVotes = parseInt(totalVotes)+1
                    }
                   
                    $(".post[data-post-id='"+postid+"'] .one-option").addClass('poll-votted-already');
                    let currentVoteCount = parseInt($(".post[data-post-id='"+postid+"'] .one-option[data-option-id='"+optionId+"']").attr('data-option-vote'));
                    console.log(currentVoteCount)
                    $(".post[data-post-id='"+postid+"'] .one-option[data-option-id='"+optionId+"']").attr('data-option-vote', (currentVoteCount+1))
                    $(".post[data-post-id='"+postid+"'] .one-option").each(function(){
                        let perOptionVotes = parseInt($(this).attr('data-option-vote'));
                        
                        let fillBar =  Math.round((perOptionVotes/totalVotes)*100);
                       
                        $(this).find('.progress-bar').css('width', fillBar+'%')
                        let ncircleImage = `<span class="option-page">${fillBar}%</span>`;
                        $(this).prepend(ncircleImage)
                        if(optionId == $(this).attr('data-option-id')){
                            $(this).find('.progress-bar-parent').prepend(votedCheckBoxImage)
                        }
                    });

                    $(".post[data-post-id='"+postid+"']").find('.select-poll-img').remove();
                    $(".post[data-post-id='"+postid+"']").find('.hide-item').removeClass('hide-item')
                    $(".post[data-post-id='"+postid+"']").find('.text-underline').removeClass('text-underline')
                  //return false;
                    $.ajax({
                                method: "POST",
                                url: endpoint+'addPollVote',
                                headers: {"Authorization": "Bearer " + st.login},
                                data: {post_id:postid, option_id:optionId },
                                success: function(serverResponse, txtStatus, request) {
                                    if(serverResponse.status == true){
                                        
                                    }
                                },
                                statusCode: {
                                    500: function(serverResponse) {
                                    
                                    },
                                    401:function(){
                                
                                    }, 
                                    422:function(e){
                                
                                    }
                                }
                        });
    
                }
            })
        }); 
})


function prependPollPost(pollData){

	let pollPost = pollData.feed; 
	let pollOptions = pollData.options; 
	
    let totalVotes = pollData.total_votes;
	chrome.storage.local.get(['list'], function(st){
		pollPost.forEach(element => {
		
			let item = '';
			let isVoted = "";
			if(element.isvoted != null){
				isVoted = "votted";
			}


			iscommented = ""
			if(element.iscommented != '0'){
			iscommented = "commented";
		}

		let isBookMark = bookmarkImages[0];
		if(element.isBookMark != null){
			isBookMark = bookmarkImages[1];
		}

			let redirectlabel = ``
	
			let title = JSON.parse(element.title);
			if(st.list){

                if(title.length>69){
                    title = JSON.parse(element.title).substring(0,69)+'...'
                }
			    let pollOptionHtml = '';
                let hideClass = 'hide-item'
                pollOptions.forEach(op=>{
                    let fillBar =  Math.round((op.count/totalVotes)*100);

                    let circleImage = `<img class="select-poll-img" src="../assets/images/poll/select-poll.png">`
                    let votedCheckbox = ``;
                    let alreadyVoteCLass = ''
                    if(pollData.voted.length){
                        circleImage = `<span class="option-page">${fillBar}%</span>`;
                        if(op.id == pollData.voted[0].poll_op_id){
                            votedCheckbox = votedCheckBoxImage;
                           
                        }
                        alreadyVoteCLass = 'poll-votted-already'
                        hideClass = '';
                    }

                 
                    pollOptionHtml += `<span data-option-vote="${op.count}" class="${alreadyVoteCLass} one-option d-block mt-1 mb-1" data-option-id="${op.id}" >
                                            ${circleImage}
                                            <span class="select-poll-text text-underline">${JSON.parse(op.poll_value)}
                                            </span>
                                            <span class="progress-bar-parent ml-3 pt-2 ${hideClass}">
                                            ${votedCheckbox}
                                            <div class="progress polled-option" data-option-id="${op.id}">
                                                <div class="progress-bar" role="progressbar" style="width: ${fillBar}%; color:#007aff" aria-valuenow="${fillBar}" aria-valuemin="0" aria-valuemax="100"></div>
                                            </div>
                                            </span>
                                        
                                        </span>`;
                });
				pollOptionHtml += `<div class="vote-c-count text-center">${totalVotes} Votes</div>`
                let IsPinLabel = `<span class="pinned-post-parent"><img class="pinned-post" src="${pinnedImageUrl}">Pinned post</span>`;


				item = `<div  data-total-votes="${totalVotes}" data-supplier-id="${element.supplier_id}" data-post-id ="${element.id}" class="row feed_strip post feed_full_width poll-post" >
				<img data-toggle="modal"  class="open-post" data-target="#myModal" src="" style="display:none;">	
				<div class="col-12 feed_icon">
                ${IsPinLabel}
					<p   class="open-post post-title"  class="tooltip-r post-title" data-toggle="tooltip" data-placement="bottom" title="${JSON.parse(element.title)}">${title}</p>
					
					<div class="row  flex-column poll-options ">
					${pollOptionHtml}
					</div>

					<img class="sup-favicon" src="${faviConUrl(element.supplier_id)}">
					<span class="post-date-time">${displayDate(element.pubdate)}</span>
					<span class="post-author"><img src="../assets/images/default/user-tag.png" class="author-image">${JSON.parse(element.author_name)}</span><br>
					<span class="pills upvote vote-btn ${isVoted}">
						<img class="down-vote" src="../assets/images/up-vote.png">
						<img  class="up-vote" src="../assets/images/upvoted-r.png">
						<span class="counter">${element.vote_count}</span>
					</span>
					<span class="pills comment-pills ${iscommented}" id="msg_icon">
						<img class="comment-default" src="../assets/images/msg_icon.png">
						<img class="blue-comment" src="../assets/images/blue-message.png">
						<span class="counter1">${element.comment_count}</span>
					</span>
					<span class="pills bookmark-btn" id="msg_icon">
						${isBookMark}
						</span>
					<span class="pills share-icons" id="share_icon" style="display:none">
						<img class="share-default" src="../assets/images/share_icon.png">
						<img class="green-share" src="../assets/images/green-share.png">
					</span>
					${redirectlabel}
					
				</div>
				</div>`; 
			} else{

			if(title.length>65){
				title = JSON.parse(element.title).substring(0,65)+'...'
			}

            let pollOptionHtml = '';
            let hideClass = 'hide-item'
            pollOptions.forEach(op=>{
                let fillBar =  Math.round((op.count/totalVotes)*100);

                let circleImage = `<img class="select-poll-img" src="../assets/images/poll/select-poll.png">`
                let votedCheckbox = ``;
                let alreadyVoteCLass = ''
                if(pollData.voted.length){
                    circleImage = `<span class="option-page">${fillBar}%</span>`;
                    if(op.id == pollData.voted[0].poll_op_id){
                        votedCheckbox = `<img class="selected-poll-img" src="../assets/images/poll/selected-poll.png">`
                    }
                    hideClass = '';
                    alreadyVoteCLass = 'poll-votted-already'
                }


                pollOptionHtml += `<span data-option-vote="${op.count}" class="${alreadyVoteCLass} one-option d-block mt-1 mb-1" data-option-id="${op.id}" >
                                        ${circleImage}
                                        <span class="select-poll-text text-underline">${JSON.parse(op.poll_value)}
                                        </span>
                                        <span class="progress-bar-parent ml-3 pt-2 ${hideClass}">
                                        ${votedCheckbox}
                                        <div class="progress polled-option" data-option-id="${op.id}">
                                            <div class="progress-bar" role="progressbar" style="width: ${fillBar}%; color:#007aff" aria-valuenow="${fillBar}" aria-valuemin="0" aria-valuemax="100"></div>
                                        </div>
                                        </span>
                                    </span>`;
            });
            pollOptionHtml += `<div class="vote-c-count text-center">${totalVotes} Votes</div>`
			item =  `<div data-total-votes="${totalVotes}" data-supplier-id="${element.supplier_id}" data-post-id ="${element.id}" class="col-4 feed_grid post post-cards poll-post" >
			<div class="row feed_strip">
			<img data-toggle="modal"  class="open-post" data-target="#myModal" src="" style="display:none;">	

			<div class="col-12 feed_icon">
				<p  class="open-post" data-toggle="modal" data-target="#myModal" class="tooltip-r" data-toggle="tooltip" data-placement="bottom"  title="${JSON.parse(element.title)}"><img class="pinned-post-before-title" src="../assets/images/poll/pinned.png">${title}</p>
					
				<div class="row  flex-column poll-options gid-poll-view">
				${pollOptionHtml}
				</div>
				<img class="sup-favicon" src="${faviConUrl(element.supplier_id)}">&nbsp;
				<span class="post-date-time">${displayDate(element.pubdate)}</span>
				<span class="post-author"><img src="../assets/images/default/user-tag.png" class="author-image">${JSON.parse(element.author_name)}</span><br>
				<span class="pills upvote vote-btn ${isVoted}">
					<img class="down-vote" src="../assets/images/up-vote.png">
					<img  class="up-vote" src="../assets/images/upvoted-r.png">
					<span class="counter">${element.vote_count}</span>
				</span>
				<span class="pills comment-pills ${iscommented}" id="msg_icon">
					<img class="comment-default" src="../assets/images/msg_icon.png">
					<img class="blue-comment" src="../assets/images/blue-message.png">
					<span class="counter1">${element.comment_count}</span>
				</span>
				<span class="pills bookmark-btn" id="msg_icon">
				${isBookMark}
			</span>
				<span class="pills share-icons" id="share_icon" style="display:none">
					<img class="share-default" src="../assets/images/share_icon.png">
					<img class="green-share" src="../assets/images/green-share.png">
				</span>
		
			${redirectlabel}
			
			</div>
			</div>
		</div>`
			}
		
			if(!$('div.post[data-post-id="'+element.id+'"]').length){
				$('.all_feeds').prepend(item)
			}

		
		});
	})
}

function getPinPost(){

    chrome.storage.local.get(['login'], function(st){
 
        $.ajax({
          method: "GET",
          url: endpoint+'getPinPostExt',
          headers: {"Authorization": "Bearer " + st.login},
          success: function(serverResponse, txtStatus, request) {
     
            if(serverResponse.status == true && serverResponse.feed.length){ 
              let feed = serverResponse.feed;
                  if(feed[0].post_type == 3){
                     prependPollPost(serverResponse); 
                 }else{
                    console.log('hererer')
                     addItemIntoFeed(feed)
                 }
                  
              }
          },
          statusCode: {
          500: function(serverResponse) {
          
            },
          401:function(){
        
          }, 
          422:function(e){
      
          }
        }
      });
    })


}




