{% load static %}
<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}">
    <link rel="shortcut icon" href="{% static 'favicon.ico' %}" />
    <style>
    .profile-img{
        text-align:center;
    }
    .profile-img img {
        width: 203px;
        height: auto;
        border-radius: 60%;
        border: 2px solid #55ACEE;
    }
    .profile-img-profile{
        text-align:center;
    }
    .profile-img-profile img {
        width: 78%;
        height: auto;
        border-radius: 60%;
        border: 2px solid #55ACEE;
        margin-top: 12%;
        margin-bottom: 8%;
    }

    span.content {
        font-size: 20px;
    }
    span.content-bar {
        font-size: 11px;
    }
    .recommended-list{
        list-style: none;
        margin-left: -2%;
        margin-top: 4%;
    }
    .follow-list{
        list-style: none;
        margin-left: 5%;
        margin-top: 4%;
    }
    .follow-list li a {
        color: #636262 !important;
        font-size: 12px;
        padding-left: 3%;
    }
    .follow-list li a:hover{
        color: #4a4a4a !important;
        font-size: 12px;
        text-decoration:none;
    }
    .follow-btn{
        background-color: #d6d6d675;
        padding: 8px;
        border-radius: 7px;
        font-size: 14px;
        font-weight: bold;
        width: 80%;
    }
    .follow-btn:hover{
        background-color: #d6d6d6;
        padding: 8px;
        border-radius: 7px;
        font-size: 14px;
        font-weight: bold;
        width: 80%;
        cursor: pointer;
        text-decoration:none;
    }

    #loadmore:hover{
        cursor: pointer;
        background-color: #d6d6d6;
    }
    #loadmore{
        background-color: #d6d6d69e;
        padding: 14px;
        border-radius: 8px;
        font-size: 13px;
    }
    .media-focus{
        border: 2px solid #55ACEE;
        padding: 20px;
        border-radius: 7px;
    }
    .tweet-likeicon{
        width: 14px;
        margin-right: 4px;
    }
    .blog-footer {
        padding: 40px 0;
        color: #999;
        text-align: center;
        background-color: #f8f8f8;
        border-top: 1px solid #e5e5e5;
    }
    .modal-content .tweet_character_counter {
        margin-top: -7%;
        font-size: 13px;
        position: absolute;
    }
    </style>
    <title>{% block title %}Tweetme : {% endblock  %}</title>
  </head>
  <body>
    {% include "navbar.html" %}
    <div class="container">
    {% block content %}
    
    {% endblock %}
    </div>
    {% include "reply-model.html" %}

    {% include "footer.html" %}
    
    
    
    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="{% static 'bootstrap/js/jquery-3.4.1.min.js' %}"></script>
    <script>
    function loadTweetContainer(tweetContainerID, fetchOneId){
    console.log("working");
    var tweets_list = [];
    var query = getParameterByName('q');
    var tweetContainer;
    tweetContainer = $('#' + tweetContainerID )
    var APIUrl=tweetContainer.attr("data-url") || "/api/tweets/";

    function updateHashLinks(){
        $(".content").each(function(data){
            var hashtagRegx = /(^|\s)#([\w\d-]+)/g
            var usernameRegx = /(^|\s)@([\w\d-]+)/g
            var newText;
            newText = $(this).html().replace(hashtagRegx, "$1<a href='/tags/$2/'>#$2</a>")
            newText = newText.replace(usernameRegx, "$1<a href='/$2/'>@$2</a>")
            $(this).html(newText)
        })
    }

    // get q parameter in url _ GET method
    function getParameterByName(name, url) {
        if (!url) url = window.location.href;
        name = name.replace(/[\[\]]/g, '\\$&');
        var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
            results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, ' '));
    }

    function formatTweet(tweetvalue){
        var didlike =tweetvalue.didlike
        var likeValue = "<img class='tweet-likeicon' src='{% static 'icons/like.png' %}' />"
        if (didlike){
            likeValue = "<img class='tweet-likeicon' src='{% static 'icons/liked.png' %}' />"
        }

        var preContent='';
        var tweetContent;
        var isReply = tweetvalue.reply
        var replyId = tweetvalue.id
        if (tweetvalue.parent){
            replyId = tweetvalue.parent.id
        }

        var openinngContainerDiv = openinngContainerDiv = "<div class='media' >"
        if (tweetvalue.id == fetchOneId){
            openinngContainerDiv = "<div class='media media-focus' >"
            setTimeout(function(){
                $('.media-focus').removeClass("media-focus")
            }, 3000)
        }

        if (tweetvalue.parent && !isReply){
            tweetvalue = tweetvalue.parent
            preContent="<span style='color:#9b9b9b;'>Retweet Via <a style='color:#9b9b9b;font-weight:bold' href='/" + tweetvalue.user.username + "/'>" + tweetvalue.user.username + "</a> On " + tweetvalue.date_display + "</span><br>"
        }else if(tweetvalue.parent && isReply){
            preContent="<span style='color:#9b9b9b;'>Reply to <a style='color:#9b9b9b;font-weight:bold' href='/" + tweetvalue.parent.user.username + "/'>@" + tweetvalue.parent.user.username + "</a></span><br>"
        }

        tweetContent ="<span class='content'>" + tweetvalue.content + "</span><br><span class='content-bar'> via : " + "<a href='" + tweetvalue.user.profile_url + "'>" + tweetvalue.user.username + "</a>" + " | " + tweetvalue.date_display +  " | " + tweetvalue.timesince + "<a href='/tweets/" + tweetvalue.id + "'> View </a> | <a class='retweet' href='/api/tweets/retweet/" + tweetvalue.id + "'>Retweet</a> | <a class='tweet-like' data-id='" + tweetvalue.id + "' href='#'>" + likeValue + "(<span id='like-counts'>" + tweetvalue.likes + "</span>)</a> | <a class='tweet-reply' data-user='" + tweetvalue.user.username + "'' data-id='" + replyId + "' href='#'>Reply</a></span>"
        var container = openinngContainerDiv + "<div class='media-body'>" + preContent + tweetContent + "</div></div><hr />"
        return container
    }


    function attach_tweet(tweetvalue, prepend, retweet_flag){
        var tweet_user = tweetvalue.user.username;
        var tweet_content = tweetvalue.content;
        var tweet_date_display = tweetvalue.date_display;
        var tweet_timesince = tweetvalue.timesince;
        var tweet_link = "/tweets/" + tweetvalue.id;
        var profile_url = tweetvalue.user.profile_url;
        var tweet_formattedhtml;
        var retweet_link = "/api/tweets/retweet/" + tweetvalue.id
        var likes = tweetvalue.likes;
        var didlike =tweetvalue.didlike
        var likeValue = "<img class='tweet-like' src='{% static 'icons/like.png' %}' />"
        if (didlike){
            likeValue = "<img class='tweet-like' src='{% static 'icons/liked.png' %}' />"
        }
        
        tweet_formattedhtml = formatTweet(tweetvalue)
        
        // if prepen is true add to above of list        
        if (prepend == true){
            tweetContainer.prepend(tweet_formattedhtml);
        }else{
            tweetContainer.append(tweet_formattedhtml);
        }
    }

    function parseTweets(){
        if (tweets_list == 0){
             tweetContainer.text("No Tweet currently found");
        }else{
            $.each( tweets_list, function( key, value ) {
                if (value.parent){
                    attach_tweet(value , false, true)
                }else{
                    attach_tweet(value , false)
                }
            });
        }
    }

    var next_url;
    var fetch_url;

    function fetchTweets(url){
        if (next_url){
            fetch_url = next_url;
        }else{
            fetch_url = APIUrl;
        }
        $.ajax({
            url: fetch_url,
            data:{'q':query},
            success: function(data , textStatus ,jqXHR){
                tweets_list = data.results;
                next_url = data.next;
                if (!next_url){
                    $("#loadmore").css('display','none')
                }
                parseTweets();
                updateHashLinks();
            },
            error: function(jqXHR, textStatus, errorThrown){
                console.log(textStatus)
                console.log(errorThrown)
            }
        });
    }

    function fetchSingle(){
        $.ajax({
            url: '/api/tweets/' + fetchOneId +'/',
            success: function(data , textStatus ,jqXHR){
                tweets_list = data.results
                parseTweets();
                updateHashLinks();
            },
            error: function(jqXHR, textStatus, errorThrown){
                console.log(textStatus)
                console.log(errorThrown)
            }
        });
    }

    if (fetchOneId){
        fetchSingle()
    }else{
        fetchTweets()
    }

    var character_counter = 140; 
    var char_count = 0;
    
    $(".tweet_form").append("<span class='tweet_character_counter' style='margin-left:20px;'> &nbsp; " + character_counter + " Left</span>")

    $(".tweet_form textarea").keyup(function( event ) {
        var txt_character_counter = $(this).parent().parent().parent().find(".tweet_character_counter");
        char_count = $(this).val().length;
        character_counter = 140 - char_count;
        txt_character_counter.text("\xa0" + character_counter);
        if (character_counter > 0){txt_character_counter.css("color", "#000");}
        else if(character_counter == 0){txt_character_counter.css("color", "#ccc");}
        else if(character_counter < 0){txt_character_counter.css("color", "red");}
    });

    $(".tweet_form").submit(function(e) {
        e.preventDefault(); // avoid to execute the actual submit of the form.

        var form = $(this);
        var url = form.attr('action');
        var this_ = $(this)

        if (character_counter < 0 ){
            console.log("Cannot Create")
        }else{
            $.ajax({
                type: "POST",
                url: '/api/tweets/create/',
                data: form.serialize(), // serializes the form's elements.
                success: function(data)
                {
                    this_.find('input[type=text],textarea').val('')
                    attach_tweet(data , true)
                    updateHashLinks();
                    $('#replyModal').modal('hide')
                }
            }); 
        }
        
    });

    $("#loadmore").click(function(){
        if (next_url){
            fetchTweets(next_url)
        }
    });

    $(document).on('click', ".retweet", function(e) {        
        e.preventDefault()
        retweet_html =  $(this)
        url = retweet_html.attr("href")
        $.ajax({
            url: url,
            success: function(data)
            {
                attach_tweet(data , true, true)
            },
            error: function(data, textStatus, errorThrown){
                console.log(data)
                alert(data.responseJSON.message)
            }
        }); 
    });

    $(document).on('click', ".tweet-like", function(e) {        
        e.preventDefault()
        this_ =  $(this)
        var tweet_id = this_.attr('data-id')
        $.ajax({
            url: '/api/tweets/like/' + tweet_id,
            success: function(data)
            {
                if (data.liked){
                    this_.find("img").attr('src', '{% static 'icons/liked.png' %}');
                    var likecount = this_.find("#like-counts").text()
                    this_.find("#like-counts").text(parseInt(likecount, 10)+1)
                }else{
                    this_.find("img").attr('src', '{% static 'icons/like.png' %}');
                    var likecount = this_.find("#like-counts").text()
                    this_.find("#like-counts").text(parseInt(likecount, 10)-1)
                }
            },
            error: function(data, textStatus, errorThrown){
                alert(data.responseJSON.message)
            }
        }); 
    });

    $(document).on('click', ".tweet-reply", function(e) {        
        e.preventDefault()
        this_ =  $(this)
        var tweet_id;
        var tweet_username;

        parent_id   = this_.attr('data-id')
        username    = this_.attr('data-user')
        content     = this_.parent().find('.content').text()
        
        $('#replyModal').modal('show');
        $('#replyModal').on("shown.bs.modal",function(){
            $('#tweetReplyArea').focus()
        })
        $('#replyModal textarea').after("<input type='hidden' value='" + parent_id + "' name='parent_id' />")
        $('#replyModal textarea').after("<input type='hidden' value='true' name='reply' />")
        $('#replyModal #reply-content').text(content)
        $('#replyModal textarea').val('@' + username + ' ');

    });

}
    </script>

    <script>{% block script %}{% endblock script %}</script>
    <script>
    $( document ).ready(function() {

        var typingtimer;
        var search_query;
        var search_input = $("#form_search input[type='text'");

        search_input.keyup(function( event ) {
          search_query = $(this).val()
          console.log("up")
          clearTimeout(typingtimer)
          typingtimer = setTimeout(doneSearchTyping, 1200)
        });

        search_input.keydown(function( event ) {
          console.log("down")
          clearTimeout(typingtimer)

        });

        function doneSearchTyping(){ 
            if(search_query){
              var url = '/?q=' + search_query;
              document.location.href = url;
            }
        }
    });

    </script>
    <script src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script>
  </body>
</html>