# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: dan@reciprocitylabs.com
# Maintained By: dan@reciprocitylabs.com


from ggrc import db
from ggrc.models.associationproxy import association_proxy
from ggrc.models.mixins import (
    deferred, Base, Titled, Slugged, Described, Timeboxed
    )
from ggrc.models.reflection import PublishOnly
from ggrc.models.object_owner import Ownable
from sqlalchemy.orm import validates


class Workflow(Ownable, Timeboxed, Described, Titled, Slugged, Base, db.Model):
  __tablename__ = 'workflows'

  #Use these states for WorkflowCycle when it is implemented
  #VALID_STATES = [u"Planned", u"Future", u"In Progress", u"Overdue", u"Finished"]

  VALID_FREQUENCIES = ["one_time", "weekly", "monthly", "quarterly", "annually", "continuous"]

  @classmethod
  def default_frequency(cls):
    return 'continuous'

  @validates('frequency')
  def validate_frequency(self, key, value):
    if value is None:
      value = self.default_frequency()
    if value not in self.VALID_FREQUENCIES:
      message = u"Invalid state '{}'".format(value)
      raise ValueError(message)
    return value

  frequency = deferred(
    db.Column(db.String, nullable=True, default=default_frequency),
    'Workflow'
    )

  workflow_objects = db.relationship(
      'WorkflowObject', backref='workflow', cascade='all, delete-orphan')
  objects = association_proxy(
      'workflow_objects', 'object', 'WorkflowObject')

  workflow_people = db.relationship(
      'WorkflowPerson', backref='workflow', cascade='all, delete-orphan')
  people = association_proxy(
      'workflow_people', 'person', 'WorkflowPerson')

  workflow_tasks = db.relationship(
      'WorkflowTask', backref='workflow', cascade='all, delete-orphan')
  tasks = association_proxy(
      'workflow_tasks', 'task', 'WorkflowTask')

  task_groups = db.relationship(
      'TaskGroup', backref='workflow', cascade='all, delete-orphan')

  cycles = db.relationship(
      'Cycle', backref='workflow', cascade='all, delete-orphan')

  _fulltext_attrs = []

  _publish_attrs = [
      'workflow_objects',
      PublishOnly('objects'),
      'workflow_people',
      PublishOnly('people'),
      'workflow_tasks',
      PublishOnly('tasks'),
      'task_groups',
      'frequency',
      'cycles',
      ]

# TODO: This makes the Workflow module dependant on Gdrive. It is not pretty.
from ggrc_gdrive_integration.models.object_folder import Folderable
Workflow.__bases__ = (Folderable,) + Workflow.__bases__
Workflow.late_init_folderable()

@@ -537,16 +537,183 @@
 lidates%0A
+from .task_group_object import TaskGroupObject%0Afrom .cycle_task_group_object import CycleTaskGroupObject%0Afrom collections import OrderedDict%0Afrom datetime import date%0A
 %0A%0Aclass 
@@ -2567,16 +2567,1167 @@
      %5D%0A%0A
+from ggrc.models.computed_property import computed_property%0Aclass WorkflowState(object):%0A%0A  _publish_attrs = %5B'workflow_state'%5D%0A%0A  @computed_property%0A  def workflow_state(self):%0A    priority_states = OrderedDict(%5B%0A      # The first True state will be returned%0A      (%22Overdue%22, False),%0A      (%22InProgress%22, False),%0A      (%22Finished%22, False),%0A      (%22Assigned%22, False),%0A      (None, False),%0A      (%22Verified%22, False)%0A    %5D)%0A%0A    cycle_objects = db.session.query(CycleTaskGroupObject)%5C%0A      .join(TaskGroupObject)%5C%0A      .filter(%0A        TaskGroupObject.object_id == self.id,%0A        TaskGroupObject.object_type == self.type,%0A        TaskGroupObject.id == CycleTaskGroupObject.task_group_object_id%0A      )%5C%0A      .all()%0A%0A    for cycle_object in cycle_objects:%0A      today = date.today()%0A      if cycle_object.end_date %3C= today:%0A        priority_states%5B%22Overdue%22%5D = True%0A      priority_states%5Bcycle_object.status%5D = True%0A%0A    for state in priority_states.keys():%0A      if priority_states%5Bstate%5D:%0A        return state%0A%0A    return None%0A%0Afrom ggrc.models.mixins import BusinessObject%0ABusinessObject.__bases__ = (WorkflowState,) + BusinessObject.__bases__%0A%0A
 # TODO: 

Add workflow_state computable property to business objects