using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Airship : MonoBehaviour
{
    public City location;
    public City destination;

    public int sterlings;
    public float fuel;
    public int maxFuel;
    public int cargoCapacity;
    public int speed;
    public int currentTonnage;

    public float baseMovement;

    public List<Contract> contracts;

    // Start is called before the first frame update
    void Start()
    {
        UpdateCargo();
    }

    // Update is called once per frame
    void Update()
    {
        if (destination != null)
        {

        }
    }

    public void SetLocation(City city)
    {
        location = city;
        transform.position = city.transform.position + Vector3.back;
    }

    public void UpdateCargo()
    {
        currentTonnage = 0;
        foreach (var contract in contracts)
        {
            currentTonnage += contract.tonnage;
            contract.Load(this);
        }
    }

    public int CurrentCargo()
    {
        return (int)currentTonnage;
    }

    public int CurrentFuel()
    {
        return (int)fuel;
    }

    public int AvailableCargo()
    {
        return cargoCapacity - currentTonnage;
    }

    public void Sell(Contract contract)
    {
        sterlings += contract.value;
        RemoveCargo(contract);
    }

    public void RemoveCargo(Contract contract)
    {
        contracts.Remove(contract);
        UpdateCargo();
    }

    public void Refuel()
    {
        if (location != null)
        {
            sterlings -= RefuelCost();
            fuel = maxFuel;
        }
    }

    public int RefuelCost()
    {
        float tonnage = maxFuel - fuel;
        if (location != null)
        {
            return (int)Math.Ceiling(tonnage * location.FuelRate());
        }
        else
        {
            return 0;
        }
    }

    public void Load(Contract contract)
    {
        contracts.Add(contract);
        UpdateCargo();
    }

    public int Speed()
    {
        return speed;
    }

    public void DeductExpenses()
    {
        sterlings -= 20;
    }

    public void ConsumeFuel(float hours)
    {
        if (destination != null)
        {
            transform.position = Vector3.MoveTowards(transform.position, destination.transform.position, hours);
            if (DistanceTo(destination) < 0.2f)
            {
                transform.position = destination.transform.position;
                location = destination;
                destination = null;
                GameManager.Instance().ActivateDocking();
            }
        }
        var consumption = 2.0f * speed * speed * hours / 24;
        fuel -= consumption;
    }

    public float DistanceTo(City otherCity)
    {
        if (otherCity == location)
        {
            return 0;
        }
        else
        {
            return Vector3.Distance(transform.position, otherCity.transform.position);
        }
    }
}
