#!/usr/bin/env python3
import json
import re
import sqlite3
import argparse
from sqlite3 import Error
from random import randint

import requests

import db
from settings import DB_LOCATION, SLACK_WEBHOOK


def create_db():

  try:
    conn = sqlite3.connect(DB_LOCATION)
    print(sqlite3.version)
  except Error as e:
    print(e)
  finally:
    conn.close()


def is_coub(url):
  regex = re.compile("^(?:http|ftp)s?:\/\/coub.com\/view\/[\d\w]+", re.IGNORECASE)
  return re.match(regex, url)


def add_coub(args):

  if args.url is None:
    print("ERROR: URL can't be empty.")
    exit(1)

  if not is_coub(args.url):
    print("ERROR: URL is not coub.")
    exit(2)

  db.add_coub(args.url)


def get_random_coub():
  library_size = db.get_library_size()
  max_views = db.get_max_coub_views()

  coubs_sample = db.get_coubs(max_views)
  coubs_sample_size = len(coubs_sample)

  random_coub_id = randint(1, library_size)

  if coubs_sample_size != 0:
    random_index = randint(0, coubs_sample_size - 1)
    random_coub_id = coubs_sample[random_index][0]

  random_coub = db.get_coub(random_coub_id)

  return random_coub


def publish(args):

  coub = get_random_coub()

  payload = {
    "text": "A work day is over.\n Human, watch a *Friday's coub #{0}* and have a nice weekend!\n {1}".format(coub.id, coub.url),
    "mrkdwn": True
  }

  r = requests.post(SLACK_WEBHOOK, data=json.dumps(payload))

  if r.status_code == 200:
    coub.viewed()
    db.update_coub(coub)
    print("Published coub (id: {0})".format(coub.id))


def show_statistic(args):
  size = db.get_library_size()
  new_coubs = db.get_new_coubs_size()

  print("Library size: {}".format(size))
  print("New coubs: {}".format(new_coubs))


def parse_args():
  DESCRIPTION = "Friday's Coub"

  parser = argparse.ArgumentParser(description=DESCRIPTION)
  subparsers = parser.add_subparsers()

  parser_add = subparsers.add_parser('add', help='Add a new coub to library')
  parser_add.add_argument('url', help='Coub URL.')
  parser_add.set_defaults(func=add_coub)

  parser_publish = subparsers.add_parser('publish', help='Publish coub to slack community')
  parser_publish.set_defaults(func=publish)

  parser_statistic = subparsers.add_parser('statistic', help='Show library statistic.')
  parser_statistic.set_defaults(func=show_statistic)

  return parser.parse_args()


def main():
  args = parse_args()
  args.func(args)


if __name__ == '__main__':
  main()


