﻿const api_key = '847B8CAD-E3E6-4298-A6E9-2FDDD1EC5DF3'

function updateModal (pk, title) {
	const targetUrl     = `https://sampatapi.areeo.ac.ir/api/Projects/GetNumOfStateProjects?appID=${api_key}&stateCode=${pk}`
	const comNameDic 	= {
	  "پژوهشكده حفاظت خاك و آبخيزداري": "آبخيزداري",
	  "پژوهشگاه بيوتکنولوژي کشاورزي": "بيوتکنولوژي",
	  "دفتر امور اقتصادي": "مدیریت و اقتصادي",
	  "مرکز فناوري اطلاعات و اطلاع رساني": "علوم و فناوری اطلاعات",
	  "مرکز ملي تحقيقات شوري": "شوری",
	  "موسسه آموزش و ترويج كشاورزي": "آموزش و ترويج",
	  "موسسه تحقيقات اصلاح و تهيه نهال و بذر": "اصلاح نهال و بذر",
	  "موسسه تحقيقات برنج کشور": "برنج",
	  "موسسه تحقيقات پنبه": "پنبه",
	  "موسسه تحقيقات ثبت و گواهي بذر و نهال": "ثبت و گواهي بذر",
	  "موسسه تحقيقات جنگلها و مراتع كشور": "جنگل و مرتع",
	  "موسسه تحقيقات خاک و آب": "خاک و آب",
	  "موسسه تحقيقات علوم باغباني": "باغبانی",
	  "موسسه تحقيقات علوم دامي کشور": " علوم دامی",
	  "موسسه تحقيقات فني و مهندسي کشاورزي": "فنی و مهندسی",
	  "موسسه تحقيقات گياه پزشكي كشور": "گياه پزشكی",
	  "موسسه تحقيقات واکسن وسرم سازي رازي": "واکسن وسرم سازی",
	  "موسسه تحقيقات كشاورزي ديم كشور": "ديم",
	  "موسسه تحقيقات علوم شيلاتي کشور": "شيلات",
	  "مرکز تحقيقات کرم ابريشم": "ابريشم",
	  "موسسه تحقيقات اصلاح و تهيه بذر چغندر قند": "چغندر قند"
	};

    $('#mapModalHeader').text(title)
    $('#mapModlaSVG').empty()
  
    // set the dimensions of the canvas
    var margin  = { top: 0, right: 30, bottom: 20, left: 30 }
    var width   = 700 - margin.left - margin.right
    var height  = 500 - margin.top - margin.bottom
  
    // Set ranges
    var xScale = d3.scaleBand().range([0, width]).padding(0.4)
    var yScale = d3.scaleLinear().range([height, 0])
  
    // Svg Init
    const svg = d3.select('#mapModlaSVG')
      .append('svg')
      .attr('viewBox', '0 0 600 530')
      .attr('xmlns', 'http://www.w3.org/2000/svg')
      .attr('version', '1.1')
      .style('margin', 'auto')
      .attr('width', width + margin.left + margin.right)
      .attr('height', height + margin.top + margin.bottom)
  
    var g = svg.append('g')
      .attr('transform',
        'translate(' + margin.left + ',' + margin.top + ')')
  
    d3.json(targetUrl)
      .then(data => {
        // Scale the range of the data in the domains

        xScale.domain(data.States.map(function (d) { return comNameDic[d.ComName]? comNameDic[d.ComName] : d.ComName }))
        yScale.domain([0, d3.max(data.States, function (d) { return d.NumOfProjects })])
  
        // Add x axis
        g.append('g')
          .attr("class", "x axis")
          .attr('transform', 'translate(0,' + height + ')')
          .call(d3.axisBottom(xScale))
          .selectAll("text")
          .attr("y", 9)
          .attr("x", 2)
          .attr("dy", ".35em")
          .attr("transform", "rotate(-25)")
          .style("text-anchor", "start");
          
  
        // Add y axis
        const yaxis = g.append('g')
          .call(d3.axisLeft(yScale).tickFormat(function (d) {
            return d
          }).ticks(10))
          .selectAll('text')
          .attr('text-anchor', 'start')
          .attr('font-family', 'Yekan')
          
  
        // Add Data bar
        var bars = g.selectAll('.bar')
          .data(data.States)
          .enter()
          .append('rect')
          .attr('class', 'bar')
          .attr('x', function (d) {
            return xScale(comNameDic[d.ComName]? comNameDic[d.ComName] : d.ComName)
          })
          .attr('y', function (d) { return yScale(d.NumOfProjects) })
          .attr('width', xScale.bandwidth())
          .attr('height', function (d) { return height - yScale(d.NumOfProjects) })
  
    })
}

function loadMap () {
	const targetUrl     = `https://sampatapi.areeo.ac.ir/api/Projects/GetNumOfRunningProjects?appID=${api_key}`
    const circleColor   = '#109b10d1'
    const textColor     = 'white'	

	const stateDict 	= {
		'00' : { title: 'مرکزي', latitude: '280.000000', longitude: '350.000000'},
		'01' : { title: 'گيلان', latitude: '280.000000', longitude: '160.000000'},
		'02' : { title: 'مازندران', latitude: '420.000000', longitude: '220.000000'},
		'03' : { title: 'آذربايجان شرقي', latitude: '150.000000', longitude: '130.000000'},
		'04' : { title: 'آذربايجان غربي', latitude: '75.000000', longitude: '120.000000'},
		'05' : { title: 'کرمانشاه', latitude: '125.000000', longitude: '320.000000'},
		'06' : { title: 'خوزستان', latitude: '225.000000', longitude: '500.000000'},
		'07' : { title: 'فارس', latitude: '450.000000', longitude: '650.000000'},
		'08' : { title: 'كرمان', latitude: '650.000000', longitude: '600.000000'},
		'09' : { title: 'خراسان رضوئ', latitude: '750.000000', longitude: '250.000000'},
		'10' : { title: 'اصفهان', latitude: '400.000000', longitude: '400.000000'},
		'11' : { title: 'سيستان وبلوچستان', latitude: '850.000000', longitude: '750.000000'},
		'12' : { title: 'كردستان', latitude: '150.000000', longitude: '250.000000'},
		'13' : { title: 'همدان', latitude: '225.000000', longitude: '300.000000'},
		'14' : { title: 'چهارمحال وبختيارئ', latitude: '320.000000', longitude: '480.000000'},
		'15' : { title: 'لرستان', latitude: '200.000000', longitude: '380.000000'},
		'16' : { title: 'ايلام', latitude: '123.000000', longitude: '400.000000'},
		'17' : { title: 'كهگيلويه وبويراحمد', latitude: '320.000000', longitude: '550.000000'},
		'18' : { title: 'بوشهر', latitude: '340.000000', longitude: '650.000000'},
		'19' : { title: 'زنجان', latitude: '220.000000', longitude: '200.000000'},
		'20' : { title: 'سمنان', latitude: '550.000000', longitude: '260.000000'},
		'21' : { title: 'يزد', latitude: '550.000000', longitude: '450.000000'},
		'22' : { title: 'هرمزگان', latitude: '600.000000', longitude: '730.000000'},
		'23' : { title: 'تهران', latitude: '390.000000', longitude: '275.000000'},
		'24' : { title: 'اردبيل', latitude: '210.000000', longitude: '110.000000'},
		'25' : { title: 'قم', latitude: '340.000000', longitude: '325.000000'},
		'26' : { title: 'قزوين', latitude: '280.000000', longitude: '230.000000'},
		'27' : { title: 'گلستان', latitude: '520.000000', longitude: '180.000000'},
		'28' : { title: 'خراسان شمالي', latitude: '650.000000', longitude: '150.000000'},
		'29' : { title: 'خراسان جنوبي', latitude: '750.000000', longitude: '450.000000'},
		'30' : { title: 'البرز', latitude: '340.000000', longitude: '240.000000'}
}

    // Create SVG element
    const svg = d3.select('#svgMap')

    d3.json(targetUrl)
      .then(data => {
        /* Define the data for the circles */
        var elem = svg.selectAll('g nodeText').data(data.States)

      /* Create and place the "blocks" containing the circle and the text */
      var elemEnter = elem.enter()
        .append('g')
        .attr('class', 'centerNode')
        .attr('transform', function (d) {
          return 'translate(' + stateDict[d.Code].latitude + ',' + stateDict[d.Code].longitude + ')'
        })

      /* Create the circle for each block */
      var circle = elemEnter.append('circle')
        .attr('fill', circleColor)
        .attr('r', function (d) {
          if (d.NumOfProjects.toString().length > 2) {
            return 28
          } else {
            return 25
          }
        })
        .on('click', function (d) {
          updateModal(d.target.__data__.Code, d.target.__data__.Name)
          var options = {
            backdrop: 'static',
            show: true
          }
          $('#mapModal').modal(options)
        })

      /* Create the text for each block */
      var text = elemEnter.append('text')
        .text(function (d) { return d.NumOfProjects })
        .attr('dy', 5)
        .attr('dx', function (d) {
          if (d.NumOfProjects.toString().length > 2) {
            return 17
          } else {
            return 12
          }
        })
        .attr('fill', textColor)
        .on('click', function (d) {
          updateModal(d.target.__data__.Code, d.target.__data__.Name)
          var options = {
            backdrop: 'static',
            show: true
          }
          $('#mapModal').modal(options)
        })

      /* Create the Title for each block */
      elemEnter.append('title')
      .text(function (d) { return d.Name })

    })
}
