import os.path
import base64
import json
from validate import *
from args import *

asset_src_schema = {
  "type":"object",
  "properties":{
    "graphics":{
      "type":"array",
      "items":{
        "type":"object",
        "properties":{
          "swf":{"type":"string"},
          "type":{"type":"number","default":1},
          "scale":{"type":"number","default":1}
        },
        "required":["swf"]
      }
    }
  },
  "required":["graphics"]
}

class Job:
  next_id = 0
  def __init__(self, in_file, base_dir = None, out_dir = None, **kwargs):
    if not os.path.isfile(in_file):
      raise Exception("Failed: couldn't open " + in_file)
    self.id = Job.next_id
    Job.next_id += 1
    self.in_file = abspath(in_file)
    split = os.path.split(self.in_file)
    self.base_dir = abspath(base_dir) if base_dir is not None else split[0]
    if not file_in_path(self.in_file, self.base_dir):
      raise Exception("Failed: " + in_file + " is not in base dir " + self.base_dir)
    self.rel_path = os.path.split(self.in_file[len(self.base_dir) + 1:])[0]
    self.out_dir = abspath(out_dir) if out_dir is not None else self.base_dir
    self.name = os.path.splitext(split[1])[0]
    self.done = False
    self.graphics = []
    #print self.in_file
    #print self.base_dir
    #print self.rel_path
    #print self.out_dir
    with open(self.in_file, mode="r") as f:
      graphics = []
      file_json = {}
      try:
        file_json = json.loads(f.read())
      except:
        raise Exception("Failed: " + in_file + " does not contain valid data")

    try:
      validate(instance=file_json, schema=asset_src_schema)
    except Exception, e:
      raise Exception("Failed: " + in_file + " " + str(e))

    for graphic_json in file_json["graphics"]:
      self.graphics.append(Graphic(split[0], graphic_json))

  def get_cmd(self):
    return {"graphics":[g.get_cmd() for g in self.graphics], "id":self.id}

  def write_results(self, data, resources):
    for i,r in enumerate(resources):
      path = os.path.join(self.out_dir, self.rel_path, "%s_%04d.png" % (self.name, i))
      with open(path, "wb") as f:
        f.write(base64.b64decode(r))
      print "resource file: " + path
    for name,details in data.iteritems():
      if len(data) == 1:
        pass
      else:
        pass


class Graphic:
  def __init__(self, folder, json):
    self.json = json
    self.swf_path = os.path.join(folder, json["swf"])
    json.pop("swf")
    with open(self.swf_path, mode="rb") as f:
      contents = f.read()
      self.swf = base64.b64encode(contents)
    
  def get_cmd(self):
    cmd = dict(self.json.items() + [("input", self.swf)])
    return cmd
