(function(Rkns) {
"use strict";

var _ = Rkns._;

var Ldt = Rkns.Ldt = {};

var Bin = Ldt.Bin = function(_renkan, _opts) {
    if (_opts.ldt_type) {
        var Resclass = Ldt[_opts.ldt_type+"Bin"];
        if (Resclass) {
            return new Resclass(_renkan, _opts);
        }
    }
    console.error("No such LDT Bin Type");
};

var ProjectBin = Ldt.ProjectBin = Rkns.Utils.inherit(Rkns._BaseBin);

ProjectBin.prototype.tagTemplate = _.template(
    '<li class="Rk-Bin-Item" draggable="true" data-image="<%- Rkns.Utils.getFullURL(static_url+\'img/ldt-tag.png\') %>" data-uri="<%=ldt_platform%>ldtplatform/ldt/front/search/?search=<%=encodedtitle%>&field=all" data-title="<%-title%>" data-description="Tag \'<%-title%>\'">' +
    '<img class="Rk-Ldt-Tag-Icon" src="<%-static_url%>img/ldt-tag.png" /><h4><%=htitle%></h4><div class="Rk-Clear"></div></li>'
);

ProjectBin.prototype.annotationTemplate = _.template(
    '<li class="Rk-Bin-Item" draggable="true" data-image="<%- Rkns.Utils.getFullURL(image) %>" data-uri="<%=ldt_platform%>ldtplatform/ldt/front/player/<%=mediaid%>/#id=<%=annotationid%>" data-title="<%-title%>" data-description="<%-description%>">' +
    '<img class="Rk-Ldt-Annotation-Icon" src="<%=image%>"/><h4><%=htitle%></h4><p><%=hdescription%></p><p>Start: <%=start%>, End: <%=end%>, Duration: <%=duration%></p><div class="Rk-Clear"></div></li>'
);

ProjectBin.prototype._init = function(_renkan, _opts) {
    this.renkan = _renkan;
    this.proj_id = _opts.project_id;
    this.ldt_platform = _opts.ldt_platform || "http://ldt.iri.centrepompidou.fr/";
    this.title_$.html(_opts.title);
    this.title_icon_$.addClass('Rk-Ldt-Title-Icon');
    this.refresh();
};

ProjectBin.prototype.render = function(searchbase) {
    var search = searchbase || Rkns.Utils.regexpFromTextOrArray();
    function highlight(_text) {
        var _e = _(_text).escape();
        return search.isempty ? _e : search.replace(_e, "<span class='searchmatch'>$1</span>");
    }
    function convertTC(_ms) {
        function pad(_n) {
            var _res = _n.toString();
            while (_res.length < 2) {
                _res = '0' + _res;
            }
            return _res;
        }
        var _totalSeconds = Math.abs(Math.floor(_ms/1000)),
            _hours = Math.floor(_totalSeconds / 3600),
            _minutes = (Math.floor(_totalSeconds / 60) % 60),
            _seconds = _totalSeconds % 60,
            _res = '';
        if (_hours) {
            _res += pad(_hours) + ':';
        }
        _res += pad(_minutes) + ':' + pad(_seconds);
        return _res;
    }

    var _html = '<li><h3>Tags</h3></li>',
        _projtitle = this.data.meta["dc:title"],
        _this = this,
        count = 0;
    _this.title_$.text('LDT Project: "' + _projtitle + '"');
    _(_this.data.tags).map(function(_tag) {
        var _title = _tag.meta["dc:title"];
        if (!search.isempty && !search.test(_title)) {
            return;
        }
        count++;
        _html += _this.tagTemplate({
            ldt_platform: _this.ldt_platform,
            title: _title,
            htitle: highlight(_title),
            encodedtitle : encodeURIComponent(_title),
            static_url: _this.renkan.options.static_url
        });
    });
    _html += '<li><h3>Annotations</h3></li>';
    _(_this.data.annotations).map(function(_annotation) {
        var _description = _annotation.content.description,
            _title = _annotation.content.title.replace(_description,"");
        if (!search.isempty && !search.test(_title) && !search.test(_description)) {
            return;
        }
        count++;
        var _duration = _annotation.end - _annotation.begin,
            _img = (
                (_annotation.content && _annotation.content.img && _annotation.content.img.src) ?
                  _annotation.content.img.src :
                  ( _duration ? _this.renkan.options.static_url+"img/ldt-segment.png" : _this.renkan.options.static_url+"img/ldt-point.png" )
            );
        _html += _this.annotationTemplate({
            ldt_platform: _this.ldt_platform,
            title: _title,
            htitle: highlight(_title),
            description: _description,
            hdescription: highlight(_description),
            start: convertTC(_annotation.begin),
            end: convertTC(_annotation.end),
            duration: convertTC(_duration),
            mediaid: _annotation.media,
            annotationid: _annotation.id,
            image: _img,
            static_url: _this.renkan.options.static_url
        });
    });

    this.main_$.html(_html);
    if (!search.isempty && count) {
        this.count_$.text(count).show();
    } else {
        this.count_$.hide();
    }
    if (!search.isempty && !count) {
        this.$.hide();
    } else {
        this.$.show();
    }
    this.renkan.resizeBins();
};

ProjectBin.prototype.refresh = function() {
    var _this = this;
    Rkns.$.ajax({
        url: this.ldt_platform + 'ldtplatform/ldt/cljson/id/' + this.proj_id,
        dataType: "jsonp",
        success: function(_data) {
            _this.data = _data;
            _this.render();
        }
    });
};

var Search = Ldt.Search = function(_renkan, _opts) {
    this.renkan = _renkan;
    this.lang = _opts.lang || "en";
};

Search.prototype.getBgClass = function() {
    return "Rk-Ldt-Icon";
};

Search.prototype.getSearchTitle = function() {
    return this.renkan.translate("Lignes de Temps");
};

Search.prototype.search = function(_q) {
    this.renkan.tabs.push(
        new ResultsBin(this.renkan, {
            search: _q
        })
    );
};

var ResultsBin = Ldt.ResultsBin = Rkns.Utils.inherit(Rkns._BaseBin);

ResultsBin.prototype.segmentTemplate = _.template(
    '<li class="Rk-Bin-Item" draggable="true" data-image="<%- Rkns.Utils.getFullURL(image) %>" data-uri="<%=ldt_platform%>ldtplatform/ldt/front/player/<%=mediaid%>/#id=<%=annotationid%>" data-title="<%-title%>" data-description="<%-description%>">' +
    '<img class="Rk-Ldt-Annotation-Icon" src="<%=image%>"/><h4><%=htitle%></h4><p><%=hdescription%></p><p>Start: <%=start%>, End: <%=end%>, Duration: <%=duration%></p><div class="Rk-Clear"></div></li>'
);

ResultsBin.prototype._init = function(_renkan, _opts) {
    this.renkan = _renkan;
    this.ldt_platform = _opts.ldt_platform || "http://ldt.iri.centrepompidou.fr/";
    this.max_results = _opts.max_results || 50;
    this.search = _opts.search;
    this.title_$.html('Lignes de Temps: "' + _opts.search + '"');
    this.title_icon_$.addClass('Rk-Ldt-Title-Icon');
    this.refresh();
};

ResultsBin.prototype.render = function(searchbase) {
    if (!this.data) {
        return;
    }
    var search = searchbase || Rkns.Utils.regexpFromTextOrArray();
    var highlightrx = (search.isempty ? Rkns.Utils.regexpFromTextOrArray(this.search) : search);
    function highlight(_text) {
        return highlightrx.replace(_(_text).escape(), "<span class='searchmatch'>$1</span>");
    }
    function convertTC(_ms) {
        function pad(_n) {
            var _res = _n.toString();
            while (_res.length < 2) {
                _res = '0' + _res;
            }
            return _res;
        }
        var _totalSeconds = Math.abs(Math.floor(_ms/1000)),
            _hours = Math.floor(_totalSeconds / 3600),
            _minutes = (Math.floor(_totalSeconds / 60) % 60),
            _seconds = _totalSeconds % 60,
            _res = '';
        if (_hours) {
            _res += pad(_hours) + ':';
        }
        _res += pad(_minutes) + ':' + pad(_seconds);
        return _res;
    }

    var _html = '',
        _this = this,
        count = 0;
    _(this.data.objects).each(function(_segment) {
        var _description = _segment.abstract,
            _title = _segment.title;
        if (!search.isempty && !search.test(_title) && !search.test(_description)) {
            return;
        }
        count++;
        var _duration = _segment.duration,
            _begin = _segment.start_ts,
            _end = + _segment.duration + _begin,
            _img = (
                _duration ?
                  _this.renkan.options.static_url + "img/ldt-segment.png" :
                  _this.renkan.options.static_url + "img/ldt-point.png"
            );
        _html += _this.segmentTemplate({
            ldt_platform: _this.ldt_platform,
            title: _title,
            htitle: highlight(_title),
            description: _description,
            hdescription: highlight(_description),
            start: convertTC(_begin),
            end: convertTC(_end),
            duration: convertTC(_duration),
            mediaid: _segment.iri_id,
            //projectid: _segment.project_id,
            //cuttingid: _segment.cutting_id,
            annotationid: _segment.element_id,
            image: _img
        });
    });

    this.main_$.html(_html);
    if (!search.isempty && count) {
        this.count_$.text(count).show();
    } else {
        this.count_$.hide();
    }
    if (!search.isempty && !count) {
        this.$.hide();
    } else {
        this.$.show();
    }
    this.renkan.resizeBins();
};

ResultsBin.prototype.refresh = function() {
    var _this = this;
    Rkns.$.ajax({
        url: this.ldt_platform + 'ldtplatform/api/ldt/1.0/segments/search/',
        data: {
            format: "jsonp",
            q: this.search,
            limit: this.max_results
        },
        dataType: "jsonp",
        success: function(_data) {
            _this.data = _data;
            _this.render();
        }
    });
};

})(window.Rkns);
