﻿
angular.module('ngNewApp', ['ngSanitize'])
  .controller('specialArticlesCtrl', ['$scope', '$http', '$q', '$filter', '$timeout', function ($scope, $http, $q, $filter, $timeout) {
    blockUI('DivspecialNews');
    $scope.itemsPerPage = 10;
    $scope.maxSize = 7;
    $scope.totalItems = 1;
    $scope.currentPage = 1;
    $scope.searchPeriodValue = "lastyear";

    $timeout(() => {
      $(".date-picker").datepicker({
        showOn: 'button',
        buttonImage: '/content/theme/images/x_office_calendar.png',
        buttonImageOnly: true,
        changeMonth: true,
        changeYear: true,
        showAnim: 'slideDown',
        duration: 'fast',
        dateFormat: 'mm/dd/yy'
      });
    });


    let selectedCountryId, fromdate, currentDate, fromdateformat,
      todate = new Date(),
      currentDateForYear = new Date(),
      lastYear = $filter('date')(currentDateForYear.setFullYear(currentDateForYear.getFullYear() - 1), "yyyy-MM-dd"),
      todateFormat = $filter('date')(todate, "yyyy-MM-dd");

    $http({
      method: 'POST',
      url: siteRoot + 'NewArticles/SpecialArticles/',
      data: { countryId: 0, fromdate: lastYear, todate: todateFormat, searchFor: "" }
    }).then(function (res) {
      $scope.data = res.data;

      $scope.totalItems = $scope.data.length;
      $scope.numPages = Math.ceil($scope.totalItems / $scope.itemsPerPage);
    }, (error) => { unblockUI('DivspecialNews'); console.log(error.data); }).then(function () {
      unblockUI('DivspecialNews');
    });

    $scope.setPage = function (pageNo) {
      $scope.currentPage = pageNo;
    };
    var currPage = 0;
    $scope.selectPage = function (cPno, $event) {
      if (currPage == cPno) return;
      currPage = cPno;
    };
    $scope.SearchArticle = function () {
      // Set the 'submitted' flag to true
      $scope.submitted = true;
      todate = new Date();
      currentDate = new Date();

      if ($scope.searchPeriodValue == 'lastweek') {
        fromdate = currentDate.setDate(currentDate.getDate() - 7);
      } else if ($scope.searchPeriodValue == 'lastmonth') {
        fromdate = currentDate.setMonth(currentDate.getMonth() - 1);
      } else if ($scope.searchPeriodValue == 'lastyear') {
        fromdate = currentDate.setFullYear(currentDate.getFullYear() - 1);
      } else if ($scope.searchPeriodValue == 'custom') {
        todate = $scope.toDate;
        fromdate = $scope.fromDate;
      }
      todateFormat = $filter('date')(todate, "yyyy-MM-dd");
      fromdateformat = $filter('date')(fromdate, "yyyy-MM-dd");

      selectedCountryId = (document.getElementById('CountryList').value != "" ? document.getElementById('CountryList').value : 0);


      if ($scope.formSearch.$valid) {
        blockUI('DivspecialNews');
        $http({
          method: 'POST',
          url: siteRoot + 'NewArticles/SpecialArticles/',
          data: { countryId: selectedCountryId, fromdate: fromdateformat, todate: todateFormat, searchFor: $scope.searchText }
        }).then(function (res) {
          $scope.data = res.data;

          $scope.totalItems = $scope.data.length;
          $scope.numPages = Math.ceil($scope.totalItems / $scope.itemsPerPage);
        }, (error) => { console.log(error); unblockUI('DivspecialNews'); }).then(function () {
          unblockUI('DivspecialNews');
        });
      } else {
        console.log("something wrong");
      }
    };

  }])
  .controller('NewsArchiveCtrl', ['$timeout', '$scope', '$http', '$q', '$filter', function ($timeout, $scope, $http, $q, $filter) {

    $scope.itemsPerPage = 25;
    $scope.maxSize = 7;
    $scope.totalItems = 1;
    $scope.currentPage = 1;
    $scope.searchPeriodValue = "lastyear";
    $scope.fromDate = $filter('date')(new Date(), "MM/dd/yyyy");
    $scope.toDate = $filter('date')(new Date(), "MM/dd/yyyy");
    var selectedCountryId, todate = new Date(), fromdate, todateFormat, fromdateformat, lastYear, sectorId, typeId;
    var currentDate = new Date();


    $timeout(() => {
      $(".date-picker").datepicker({
        showOn: 'button',
        buttonImage: '/content/theme/images/x_office_calendar.png',
        buttonImageOnly: true,
        changeMonth: true,
        changeYear: true,
        showAnim: 'slideDown',
        duration: 'fast',
        dateFormat: 'mm/dd/yy'
      });
    });

    $scope.$watch('searchPeriodValue', (n, o) => {
      SetDatesBySearchPeriodValue().then(() => {
        if (n === o) {
          blockUI('DivNewsArchive');
          $http({
            method: 'POST',
            url: siteRoot + 'NewArticles/NewsArchive/4',
            data: { countryId: 0, SearchType: 0, SearchSector: 0, 'fromdate': fromdateformat, 'todate': todateFormat, searchFor: "", searchTicker: "", searchCompany: "", isIslamic: false }
          }).then(function (res) {
            $scope.data = res.data;
            $scope.totalItems = $scope.data.length;
            $scope.numPages = Math.ceil($scope.totalItems / $scope.itemsPerPage);
          }).then(function () {
            unblockUI('DivNewsArchive');
          });
        }
      });
    });
    function SetDatesBySearchPeriodValue() {
      currentDate = new Date();
      return new Promise((resolve, reject) => {
        if ($scope.searchPeriodValue === 'lastweek') {
          fromdate = currentDate.setDate(currentDate.getDate() - 7);
        } else if ($scope.searchPeriodValue === 'lastmonth') {
          fromdate = currentDate.setMonth(currentDate.getMonth() - 1);
        } else if ($scope.searchPeriodValue === 'lastyear') {
          fromdate = currentDate.setFullYear(currentDate.getFullYear() - 1);
        } else if ($scope.searchPeriodValue === 'custom') {
          todate = $scope.toDate;
          fromdate = $scope.fromDate;
        }
        todateFormat = $filter('date')(todate, "yyyy-MM-dd");
        fromdateformat = $filter('date')(fromdate, "yyyy-MM-dd");

        $scope.fromDate = $filter('date')(fromdate, "MM/dd/yyyy");
        $scope.toDate = $filter('date')(todate, "MM/dd/yyyy");
        return resolve("success");
      });
    };
    $scope.setPage = function (pageNo) {
      $scope.currentPage = pageNo;
    };
    var currPage = 0;
    $scope.selectPage = function (cPno, $event) {
      if (currPage == cPno) return;
      currPage = cPno;
    };
    $scope.SearchArchive = function () {

      SetDatesBySearchPeriodValue().then((res) => {
        // Set the 'submitted' flag to true
        $scope.submitted = true;
        selectedCountryId = (document.getElementById('CountryList').value != "" ? document.getElementById('CountryList').value : 0);
        sectorId = (document.getElementById('SearchSector').value != "" ? document.getElementById('SearchSector').value : 0);
        typeId = (document.getElementById('SearchType').value != "" ? document.getElementById('SearchType').value : 0);

        blockUI('DivNewsArchive');
        $http({
          method: 'POST',
          url: siteRoot + 'NewArticles/NewsArchive/' + typeId,
          data: { countryId: selectedCountryId, SearchType: sectorId, SearchSector: sectorId, fromdate: fromdateformat, todate: todateFormat, searchFor: $scope.searchText, searchTicker: $scope.searchTicker, searchCompany: $scope.searchCompany, isIslamic: $scope.searchIslamic }
        }).then(function (res) {
          $scope.data = res.data;
          $scope.totalItems = $scope.data.length;
          $scope.currentPage = 1;
          $scope.numPages = Math.ceil($scope.totalItems / $scope.itemsPerPage);
        }).then(function () {
          unblockUI('DivNewsArchive');
        });
      });
    };
  }])
  .controller('NewsDetailMostViewed', ['$scope', '$http', '$q', '$filter', function ($scope, $http, $q, $filter) {
    blockUI('DivNewsDetail');

    $http({
      method: 'GET',
      url: siteRoot + 'NewArticles/NewsDetail/',
    }).then(function (res) {
      $scope.data = res.data;
    }).then(function () {
      unblockUI('DivNewsDetail');
    });
  }])
  .controller('NewsAnnouncements', ['$scope', '$http', '$q', '$filter', function ($scope, $http, $q, $filter) {
    blockUI('DivNewsAnnouncement');
    $scope.itemsPerPage = 25;
    $scope.maxSize = 7;
    $scope.totalItems = 1;
    $scope.currentPage = 1;
    $scope.searchFilter = '';
    $scope.filteredData = {};
    $scope.companyId = undefined;
    $scope.countryId = '0';
    $scope.ticker = '';
    $scope.countryId = '';
	  let currPage = 1;
    let todateFormat, fromdateformat;
    $scope.init = ((newsObj) => {
      $scope.countryId = parseInt(newsObj.countryId) > 0 ? newsObj.countryId.toString():'0';
      $scope.searchFilter = newsObj.ticker;
      $scope.fromDate = $filter('date')(parseInt(newsObj.minDate.slice(6,-2)), 'dd/MM/yyyy');
      $scope.toDate = $filter('date')(parseInt(newsObj.maxDate.slice(6, -2)), 'dd/MM/yyyy');
		  $(".date-picker").datepicker({
			  showOn: 'button',
			  buttonImage: '/content/theme/images/x_office_calendar.png',
			  buttonImageOnly: true,
			  changeMonth: true,
			  changeYear: true,
			  showAnim: 'slideDown',
			  duration: 'fast',
			  dateFormat: 'dd/mm/yy'
          });
          loadNews();
	  });
    $scope.setPage = function (pageNo) {
      $scope.currentPage = pageNo;
    };
   
    $scope.selectPage = function (cPno, $event) {
      if (currPage == cPno)
        return;
      currPage = cPno;
      //selectedCountryId = (document.getElementById('CountryList').value !== "" ? document.getElementById('CountryList').value : 0);

      if ($scope.formSearch.$valid) {
		  loadNews();       
      } 
    };

    $scope.SearchCorporateNews = function () {
		//selectedCountryId = (document.getElementById('CountryList').value !== "" ? document.getElementById('CountryList').value : 0);     
		  if ($scope.formSearch.$valid) {
			  loadNews();
		  }
	  };
	  function loadNews() {
		  blockUI('DivNewsAnnouncement');
		  fromdateformat = $filter('date')($scope.fromDate, "yyyy-MM-dd");
      todateFormat = $filter('date')($scope.toDate, "yyyy-MM-dd");
		  $http({
			  method: 'POST',
			  url: siteRoot + 'Tools/Announcements/',
              data: { countryId: $scope.countryId, fromdate: fromdateformat, todate: todateFormat, PageId: currPage, searchFor:$scope.searchFilter }
		  }, (error) => { unblockUI('DivNewsAnnouncement'); console.log(error.data); }).then(function (res) {
              $scope.data = res.data;
              $scope.totalItems = $scope.data[0].TotalNews;
              $scope.numPages = Math.ceil($scope.totalItems / $scope.itemsPerPage);
		  }).then(function () {
			  unblockUI('DivNewsAnnouncement');
		  }).catch((e) => {
			  console.log(e);
			  unblockUI('DivNewsAnnouncement');
		  });
	  }

      //$scope.$watch('searchFilter', (n,o) => {
      //    if (n !== undefined)
      //        loadNews();

      //});
    
  }])
  .controller('businessNewsDetailCtrl', ['$scope', '$http', '$q', '$filter','$log', function ($scope, $http, $q, $filter,$log) {
    $scope.newsId = undefined;
    let indicatorDetail = [];
    $scope.init = ((newsId) => {
      $scope.newsId = parseInt(newsId);
      blockUI('DivNewsDetail');

      $http({
        method: 'GET',
        url: siteRoot + 'NewArticles/BussinessNewsDetail/'+newsId,
      }).then(function (res) {
        indicatorDetail = res.data.IndicatorsCharts;
      }).then(function () {
        unblockUI('DivNewsDetail');
        let chartDivs = document.getElementsByClassName('business-news-chart');
        angular.forEach(chartDivs, (elem) => {
          let chartDataFormat = [];         
          let munit = elem.attributes["data-m-unit"].value;
          let currency = elem.attributes["data-currency"] ? elem.attributes["data-currency"].value : '';
          let factId = parseInt(elem.attributes["data-fact-id"].value);
          let chartData = $.map(indicatorDetail, (ind) => { if (ind.ESDFactID === factId) return ind; });
          let millionFactor = munit ? 1000000 : 1;
          $.each(chartData, (i, v)=> {
            chartDataFormat.push([parseInt(v.AsofDate.slice(6, -2)), v.Value*millionFactor])
          });
          chartDataFormat = chartDataFormat.sort((a, b) => {            
              return a[0] < b[0] ? -1 : 1;
          });
          CreateCharts(elem, chartDataFormat, currency);
        });
      });

    });
    function CreateCharts(objid, indicatorData, currency) {    
     $(objid).highcharts({
        chart: {
          marginTop: 25         
        },
        yAxis: {
          title: {
            align: 'high',
            offset: 0,
            text: currency,
            rotation: 0,
            y: -10,
            style: {
              fontWeight:'bold'
            }
          },
          labels: {
            formatter: function () { 
              return $filter('AbbrOrWNOrDec')(parseFloat(this.value),2);
            },
            style: {
              color: '#222'
            }
          },
          lineColor: '#ccc',
          lineWidth:1,
          gridLineColor: '#ececec',
          alternateGridColor: '#FeFeFe',
        },
        xAxis: {
          type: 'datetime',
          labels: {
            formatter: function () {
              return Highcharts.dateFormat("%m-%Y", this.value);
            },
            style: {
              color: '#222'
            }
          }
        },
        title: {
          text: ''
        },
        scrollbar: {
          enabled: false
        },
        rangeSelector: {
          enabled: false
        },
        navigator: {
          enabled: false
        },
        exporting: {
          enabled: false
        },
        legend: {
          enabled: false
        },
        credits: {
          enabled: false
        },
        tooltip: {
          headerFormat: '',
          useHTML: true,
          formatter: function () {
            return `<b>${Highcharts.dateFormat('%b %e, %Y', new Date(this.x))} :</b>${currency}${$filter('AbbrOrWNOrDec')(parseFloat(this.y), 2)} `;
          }
        },
        plotOptions: {
          line: {
            turboThreshold: 0,
            marker: {
              enabled: true,
              radius: 3,
              lineWidth: 2,
              lineColor:'#52658f',
              states: {
                hover: {
                  fillColor: "#52658f",
                  radius: 4
                }
              },
              symbol: "circle"
            },
            shadow: false,
            states: {
              hover: {
                enabled: true,
                lineWidth: 2
              }
            }
          }
        },
        series: [{
          data: indicatorData,
          color: '#52658f',
          type: 'line',
          tooltip: {
            valueDecimals: 2
          }
        }]
      });
    }

  }])
  .controller('nonListedCompanyNewsDetailCtrl', ['$scope', '$http', '$q', '$filter', '$timeout', function ($scope, $http, $q, $filter, $timeout) {
    let facts = {},
      factDetail = {};
    $scope.init = ((companyId,sectorId) => {
      blockUI('ratio-charts');
      $http({
        method: 'POST',
        url: siteRoot + 'NewArticles/CompanyNewsDetail/',
        data: { id: companyId, sid: sectorId }
      }).then(function (res) {
        facts = res.data.facts;
        
        factDetail = res.data.detail;
        createChartsDivs();
        processCharts();
      }, (error) => { unblockUI('ratio-charts'); console.log(error.data); }).then(function () {

        }).finally(() => {
          unblockUI('ratio-charts');
        });
    });
    function createChartsDivs() {
      let uniqueFacts = factDetail.map((f) => { return f.ESDFact; }).uniqueArray();
      uniqueFacts.map((fact) => {
        let tempFact = factDetail.map((el) => { if (el.ESDFact === fact) return el; }).clean().firstOrDefault();

        $('.chart-holder').append(`
        <div class="space-15"></div>          
           <div id="NewCompanyChart${tempFact.ESDFactID}" data-fact-id="${tempFact.ESDFactID}" class="comany-news-chart const-ltr"></div>              
          </div>
      `);
      });
    }
    function processCharts() {
      angular.forEach(document.getElementsByClassName('comany-news-chart '), function (el) {
        let factId = parseInt(el.attributes['data-fact-id'].value);
        let currentFact = factDetail.map((el) => { if (el.ESDFactID === factId) return el; }).clean().firstOrDefault();
        let cats = factDetail.map((el) => { return el.Year; }).uniqueArray().sortAsc();
        let chartData = [];
        cats.map((y) => {
          chartData.push(factDetail.map((el) => { if (el.Year === y && el.ESDFactID === factId) return { y: el.Value, title: el.ESDFact } }).clean().firstOrDefault());          
        });
        
        createChart(el,`<p class="text-center"><b> ${currentFact.ESDFact}</b></p><p class="text-center"> (${currentFact.Unit}) </p>`, cats, chartData);

      });
    }
    function createChart(element, title, chartCats, chartData) {
      Highcharts.chart(element, {
        chart: {
          type: 'column',
          borderColor: "#ccc",
          borderRadius: 1,
          borderWidth: 1,
          backgroundColor: null,
          panning: false,
          marginBottom: 60,
          //events: {
          //  load: function () {
          //    var points = []
          //    this.series.forEach(function (entry) {
          //      entry.data.forEach(function (theData) {
          //        points.push(theData.y);
          //      });
          //    });
          //    this.yAxis[0].update({
          //      max: Math.max.apply(Math, points)
          //    });
          //  }
          //}
        },
        title: {
          align: 'center',
          floating: false,
          margin: 15,
          style: {},
          text: '',
          useHTML: true
        },
        watermark: {
          yAxis: 280
        },
        subtitle: {
          align: 'center',
          floating: false,
          style: { "color": "#666666" },
          text: title,
          useHTML: true,
        },
        yAxis: [{
          gridLineColor: '#ececec',
          min: chartData.map((el) => { return el.y; }).sortAsc().firstOrDefault(),
          lineColor: '#ccc',
          lineWidth: 1,
          title: '',
          className: 'ltr',
          labels: {
            formatter: function () {
              let factor = parseInt(this.value) === parseFloat(this.value) ? 0 : 2;
              return $filter('WNOrDec')(this.value, factor);
            },
            style: {
              color: '#222',
            }
          },
          //tickPositioner: function () {
            
          //  var positions = [],
          //    tick = Math.floor(this.dataMin) - (Math.floor(this.dataMin) / 15),
          //    increment = Math.ceil((this.dataMax - this.dataMin) / 5); 
            
          //  if (this.dataMax !== null && this.dataMin !== null) {
          //    for (tick; tick - increment <= this.dataMax; tick += increment) {
          //      positions.push(tick);
          //    }
          //  }
          //  return positions;
          //}
        }],
        legend: {
          enabled: false
        },
        xAxis: {
          labels: {
            formatter: function () {
              return this.value;
            },
            style: {
              color: '#222'
            }
          },
          categories: chartCats
        },
        credits: {
          enabled: false
        },
        tooltip: {
          style: {
            opacity: '1.0'
          },
          formatter: function () {
            let factor = parseInt(this.y) === parseFloat(this.y) ? 0 : 2;
            return $filter("AbbrOrWNOrDec")(this.y, factor);
          }
        },
        series: [{
          name: 'cap indices',
          data: chartData,
          dataLabels: {
            enabled: true,
            formatter: function () {
              let factor = parseInt(this.y) === parseFloat(this.y) ? 0 : 2;
              return $filter('number')(this.y, factor);
            },
            useHTML: true
          }
        }]
      });
    }
  }])
  ;