#   Eve W-Space
#   Copyright 2014 Andrew Austin and contributors
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
import csv

from django.db import models
from django.conf import settings
import eveapi

from core.models import Type, Location
from API.models import CorpAPIKey
from core.models import Corporation, Alliance
from Map.models import System, MapSystem, Map
from API import cache_handler as handler


User = settings.AUTH_USER_MODEL


class POS(models.Model):
    """Represents a POS somewhere in space."""
    system = models.ForeignKey(System, related_name="poses")
    planet = models.IntegerField()
    moon = models.IntegerField()
    towertype = models.ForeignKey(Type, related_name="inspace")
    corporation = models.ForeignKey(Corporation, related_name="poses")
    posname = models.CharField(max_length=100, blank=True, null=True)
    fitting = models.TextField(blank=True, null=True)
    # Using CCP's status codes here for sanity with API checks
    status = models.IntegerField(choices=((0, 'Unanchored'),
                                          (1, 'Anchored'),
                                          (2, 'Onlining'),
                                          (3, 'Reinforced'),
                                          (4, 'Online')))

    # This should be the time the tower exits RF
    # TODO: add a validator to make sure this is only set
    #       if status = 3 (Reinforced)
    rftime = models.DateTimeField(null=True, blank=True)
    updated = models.DateTimeField()
    # These values will be set by the TSV parser from d-scan data if available
    guns = models.IntegerField(null=True, blank=True)
    ewar = models.IntegerField(null=True, blank=True)
    sma = models.IntegerField(null=True, blank=True)
    hardener = models.IntegerField(null=True, blank=True)
    # This is a short comment that is displayed as a warning
    warpin_notice = models.CharField(blank=True, null=True, max_length=64)

    class Meta:
        ordering = ['system__name', 'planet', 'moon']

    @classmethod
    def update_from_import_list(cls, system, import_list):
        """
        Imports starbases from YAML importer.
        """
        for pos in import_list:
            planet = pos['planet']
            moon = pos['moon']
            warpin = pos['warpin']
            status = pos['status']