﻿// JScript File

Ext.namespace('FinnKodeWeb');

FinnKodeWeb.SearchResultGrid = function(config) {
    config = config || {};

    var searchResultRecord = Ext.data.Record.create([
    { name: 'bookId', mapping: '@bookId', type: 'string' },
    { name: 'bookSectionId', mapping: '@bookSectionId', type: 'string' },
    { name: 'objectId', mapping: '@objectId', type: 'string' },
    { name: 'score', mapping: '@score', type: 'int' },
    { name: 'hitReasonVal', mapping: '@htv', type: 'int' },
    { name: 'hitReasonDesc', mapping: '@htd', type: 'string' },
    { name: 'Kilde', mapping: '@bookTitle' },
    { name: 'Kode', mapping: 'code' },
    { name: 'Term', mapping: 'title' }
    ]);

    var xmlSearchResultsReader = new Ext.data.XmlReader({
        record: 'record',
        id: '@objectId'
    },
    searchResultRecord);

    var httpProxyCommitSearch = new Ext.data.HttpProxy({
        url: 'FinnKodeWS/SearchService.svc/CommitSearch',
        headers: this.header || { 'Content-Type': 'application/json;charset=utf-8' },
        method: 'POST',
        timeout: 120000
    });
    var requestExceptionHandler = function(conn, response, options) {
        var xhr = response;
    };
    var connection = httpProxyCommitSearch.getConnection();
    connection.addListener('requestexception', requestExceptionHandler);

    var gridStore = new Ext.data.Store({
        proxy: httpProxyCommitSearch,
        reader: xmlSearchResultsReader
    });

    var columnTipRenderer = function(cellValue, cellMetadata, record, rowIndex, colIndex, store) {
        cellMetadata.attr = "ext:qtip=\"" + cellValue + "\" ext:qtitle=\"" + record.get("Kode") + "\"";
        return cellValue;
    };

    config.store = gridStore;
    config.columns = [
                { header: "BookId", width: 0, hidden: true, hideable: false, dataIndex: 'bookId' },
                { header: "BookSectionId", width: 0, hidden: true, hideable: false, dataIndex: 'bookSectionId' },
                { header: "ObjectId", width: 0, hidden: true, hideable: false, dataIndex: 'objectId' },
                { header: "Score", width: 30, sortable: true, hidden: true, dataIndex: 'score' },
                { header: "Kilde", width: 150, sortable: true, hidden: !(config.showSource), dataIndex: 'Kilde' },
                { header: "Kode", width: 80, sortable: true, dataIndex: 'Kode', fixed: true },
                { header: "Term", width: 440, sortable: true, dataIndex: 'Term', renderer: columnTipRenderer },
                { header: "", width: 39, fixed: true, sortable: false, hidden: false, dataIndex: 'hitReasonVal',
                    renderer: function(value, metaData, record, rowIndex, colIndex, store) {
                        metaData.attr = 'ext:qtip="' + record.get("hitReasonDesc") + '"';
                        var resultHtml = "";
                        if (value == 1 || value == 3 || value == 5 || value == 7) {
                            resultHtml = '<img src="images/text_view.png"/>';
                        }
                        if (value != 1) {
                            resultHtml += '<img src="images/transform.png"/>';
                        }
                        return resultHtml;
                    }
                },
                { header: "Årsak", width: 250, sortable: true, hidden: true, dataIndex: 'hitReasonDesc' }
            ];

    // call superclass constructor
    FinnKodeWeb.SearchResultGrid.superclass.constructor.call(this, config);

    this.search = function(searchTerm, sources) {
        MsgSvc.addMsg({
            Category: 'Search',
            Action: 'BeforeSearch',
            Label: 'Utrykk: ' + searchTerm + ', Kilder: ' + sources
        });
        gridStore.load({
            params: Ext.encode({
                searchExpression: searchTerm,
                sources: sources
            }),
            callback: searchReturnedHandler,
            add: false,
            scope: this
        });
    };

    var searchReturnedHandler = function(recordBlock, options, success) {
        // scope is the store
        var params = Ext.util.JSON.decode(options.params);
        if (!success) {
            MsgSvc.addMsg({
                ShowAlertInfo: true,
                MaskElement: this.getUpdater().el,
                Category: 'Search',
                Action: 'AfterSearchFailure',
                Label: 'Søk feilet. Utrykk: ' + params.searchExpression
            });
            return;
        }
        if (recordBlock.length == 100) {
            this.setTitle(String.format('Søkeresultat - For mange treff. {0} vist', recordBlock.length));
        }
        else {
            this.setTitle(String.format('Søkeresultat - Antall treff: {0}', recordBlock.length));
        }
        var sources = new String();
        for (var idx = 0; idx < params.sources.length; idx++) {
            if (params.sources[idx].Selected) {
                var searchExpression = params.searchExpression;
                var codeBookId = params.sources[idx].SearchSourceId;
                finnkode.kith.no.istatisticsservice.RegisterSearchExpression(searchExpression, codeBookId, recordBlock.length);
                sources = sources.concat((idx > 0 ? ', ' : '') + codeBookId);
            }
        }
        if (recordBlock.length > 0) {
            MsgSvc.addMsg({
                Category: 'Search',
                Action: 'AfterSearchSuccess',
                Label: 'Søk lykkes. Utrykk: ' + params.searchExpression,
                TrackLabel: sources + ': ' + params.searchExpression
            });
        }
        else {
            MsgSvc.addMsg({
                Category: 'Search',
                Action: 'AfterSearchEmpty',
                Label: 'Ingen treff. Utrykk: ' + params.searchExpression,
                TrackLabel: sources + ': ' + params.searchExpression
            });
        }
    };

    var rowClicked = function(grid, rowIndex, e) {
        var record = grid.getStore().getAt(rowIndex);
        var rowBookId = record.get('bookId');
        var rowBookSectionId = record.get('bookSectionId');
        var rowObjectId = record.get('objectId');
        MsgSvc.addMsg({
            Category: 'SearchNavigator',
            Action: 'Navigate',
            Label: rowBookId + ' - ' + rowBookSectionId + ' - ' + rowObjectId
        });
        NavigateTo(rowBookId, rowBookSectionId, rowObjectId);
    };
    this.addListener('rowclick', rowClicked, this);

};

Ext.extend(FinnKodeWeb.SearchResultGrid, Ext.grid.GridPanel, {
    loadMask: { msg: 'Laster data' },
    viewConfig: {
        autoFill: true,
        emptyText: 'Ingen treff. Kontroller søkeord og søkekilder',
        forceFit: true,
        columnsText: 'Kolonner',
        sortAscText: 'Stigende sortering',
        sortDescText: 'Synkende sortering'
    },
    autoWidth: true,
    title: 'Søkeresultat',
    border: false
});


