/*
    JSPWiki - a JSP-based WikiWiki clone.
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); fyou may not use this file except in compliance
    with the License.  You may obtain a copy of the License at
       http://www.apache.org/licenses/LICENSE-2.0
    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
*/
/*eslint-env browser*/
/*global $, Class, Events, Snipe  */
/*
Class: Snipe.Sections
    This class implement section based editing in Snipe.
    Based on the selected section, the Snipe textarea will be filled with a
    part of the full content of the main textarea.
    At all times the main textarea will contain the full text.

    This class keeps track for the current list of page section titles.

    The set of sections is generated by the parser() callback handler.
    That parser returns an array of section "descriptors":
>    [ {title:text, start:char-offset, indent:indentation-level}, ... ]


Depends:
    Snipe

Example:
(start code)
    div.cage
      div.sections
        button.btn.btn-default
          span.icon-bookmark
          span.caret
        ul.dropdown-menu[data-hover-parent="div"]
          li  a first
          li  a ..
          li  a.dropdown-divider
          li  a ..

    new Snipe.Sections( snipe, {
        main: <main textarea>
        menu: <ul dropdownmenu>,
        parser: function(text){ .. return [[{title, start, depth}],..]; }
    });
(end)
*/

Snipe.Sections = new Class({

    Implements: [Events],
    Binds: ["show","update","action"],

    options: {
        //main
        //menu
        //parser: function(text){ returns [[title,start,depth]..] }
        all: "( all )".localize(),
        sections: ".sections",
        startOfPage: "Start of Page".localize()
    },

    initialize: function(snipe, options){

        var self = this;

        self.snipe = snipe;
        self.main = options.main;
        self.parser = options.parser;

        if( options.menu ){

            self.list = options.menu.addEvent("click:relay(a)", self.action);

        }

        self.parse();
        self.action( location.search );  //url?section=0..n
        self.menu();

        //finally, connect to the update event of snipe !
        snipe.addEvent( "change", self.update );
    },

    /*
    Function: parse
        Invoke the external parser on the contents of the main textarea.
        This external parser should return an array with an entry for each section:
        [ {title:text, start:char-offset, depth:nesting level}, ... ]

        >        0 : start-of-page (if applicable) => title=s-1 => cursor=-1
        >        1..n : page sections              => title=s0..sn => cursor=0..n
    */
    parse: function( ){

        this.sections = this.parser( this.main.value );

    },

    /*
    Function: menu
        UPDATE/RFEFRESH the section dropdown-menu.
        Highlight the current item.

    (start code)
        ul.dropdown-menu
            li
                a.indent-0.section-2 (all)
            li
                a.indent-0.section-1 Start Of Page
            li.divider
            li
                a.indent-0.section0 Title-Section-0
            li
                a.indent-0.section1 Title-Section-1
            ...
            li
                a.indent-0.section99 Title-Section-2
    (end)
    */
    menu: function( ){

        //console.log("menu", this.current, this.sections.length, this.sections);

        var data = [],
            list = this.list,
            options = this.options,
            current = this.current,
            sections = this.sections,

            addItem = function(item, index){
                data.push("li" + (index == current ? ".active" : ""),[
                    "a.text-indent-" + item.depth + ".section" + index, { html:item.title }
                ]);
            };

        if( list ){

            addItem({ depth:0, title:options.all }, -2);

            if( sections[0] ){

                if( sections[0].start > 0 ){
                    addItem({ depth:0, title:options.startOfPage }, -1);
                }
                data.push( "li.divider" );
                sections.each( addItem );
            }

            list.empty().adopt( data.slick() );

            list.getParent().ifClass( current >= -1, "section-selected");

        }

    },

    /*
    Function: update
        This function handles the propagation of changes from snipe to the main textarea.
        It is triggered by a change event on snipe.
    */
    update: function(){

        var self = this,
            main = self.main,
            work = self.snipe.get("value"),
            s = main.value;

        //insert \n to ensure the next section always starts on a new line.
        if( work.slice(-1) != "\n" ){ work +="\n"; }

        //console.log("change txta: from="+self.begin+ " end="+self.end);
        if( work != s.slice(self.begin, self.end) ){

            main.value = s.slice(0, self.begin) + work  + s.slice(self.end);

            self.end = self.begin + work.length;

            self.parse();
        }
        self.menu(); //always update menu, independent of the content of main
    },

    /*
    Function: action
        This function copies the selected section from the main to the snipe textarea.
        It is invoked at initialization and through click handlers in the
        section dropdown menu.

    Arguments:
        item - index of selected section: all(-2), -1, 0..n
    */
    action: function( item ){

        var self = this,
            main = self.main.value,
            sections = self.sections,
            begin = 0,
            end = main.length;

        if( item ){

            //item.target => event.target; this is an onclick invocation!
            if( item.target ){ item = item.target.className; }

            //section-2=All, section-1=StartOfPage, section0..section99=rest
            item = parseInt(( item.match( /section=?(-?\d+)/ )||[,-2])[1]);

            if( item == -1 ){

                //show the Start Of Page, prior to the first real section
                end = sections[0].start;

            } else if(item >= 0  && sections[item] ){

                begin = sections[item].start;
                if( sections[item + 1] ){ end = sections[item + 1].start; }

            }

            self.current = item;

        }

        self.begin = begin;
        self.end = end;

        //finally set the new snipe value
        //note: this triggers a change event, and calls update()
        self.snipe.set("value", main.slice(begin, end) );

        return false; //stop click event propagation

    }

});