﻿using System;
using UnityEngine;
using UnityEngine.UI;

public class UIScaler : MonoBehaviour
{
    const float equator = 40075000;

    public float multiplier = 1;
    public Text textfield;
    public RectTransform leftLine;
    public RectTransform rightLine;
    public RectTransform horizontalLine;

    private int[] displayValues = {10000000, 5000000, 2000000, 1000000, 500000, 200000, 100000, 50000, 20000, 10000, 5000, 2000, 1000, 500, 200, 100, 50, 20, 10, 5, 2, 1};

    private OnlineMaps map;

    private void Start()
    {
        map = OnlineMaps.instance;
        map.OnChangeZoom += UpdateScaler;
        UpdateScaler();
    }

    private void UpdateScaler()
    {
        int s;
        if (map.zoom < 5) s = Mathf.RoundToInt(equator / (1 << map.zoom) * multiplier * map.zoomCoof * map.width / OnlineMapsUtils.tileSize);
        else s = Mathf.RoundToInt(OnlineMapsUtils.DistanceBetweenPoints(map.topLeftPosition, map.bottomRightPosition).x * 1000 * multiplier);

        int dv = displayValues[0];

        for (int i = 0; i < displayValues.Length; i++)
        {
            if (s > displayValues[i])
            {
                dv = displayValues[i];
                break;
            }
        }

        float c = (float) dv / s / 2;
        c = c * horizontalLine.rect.width;

        leftLine.anchoredPosition = new Vector3(c, leftLine.anchoredPosition.y, 0);
        rightLine.anchoredPosition = new Vector3(-c, rightLine.anchoredPosition.y, 0);

        bool isKM = dv >= 1000;

        if (isKM) textfield.text = dv / 1000 + " km";
        else textfield.text = dv + " m";
    }
}