#!/usr/bin/env python3
import shuffler_tools as st
import shuffler_geo as geo
import gi
gi.require_version("Wnck", "3.0")
from gi.repository import Wnck
import sys
from shuffler_tools import app_path
import subprocess


"""
WindowShuffler
Author: Jacob Vlijm
Copyright © 2017-2018 Ubuntu Budgie Developers
Website=https://ubuntubudgie.org
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or any later version. This
program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details. You
should have received a copy of the GNU General Public License along with this
program.  If not, see <https://www.gnu.org/licenses/>.
"""


def move_win(col, row, playfield):
    totalspan = [[col, row], [col + xsize - 1, row + ysize - 1]]
    y_offs = st.get_yshift(curr_subject)
    trg = st.windowtarget(
        totalspan, xycoords[0], xycoords[1], playfield, y_offs,
    )
    st.shuffle(
        curr_subject,
        trg[0], trg[1], trg[2], trg[3],
    )


def toggle_max():
    screendata = Wnck.Screen.get_default()
    screendata.force_update()
    curr_subject = screendata.get_active_window()
    ismax = curr_subject.is_maximized()
    if ismax:
        curr_subject.unmaximize()
    else:
        curr_subject.maximize()


def move_window(col, row):
    win_geodata = geo.get_windows_oncurrent(screendata)
    wins = win_geodata["windows"]
    playfield = st.calc_playfield(win_geodata)
    try:
        if all([
            curr_subject in wins,
            st.check_windowtype(curr_subject),
        ]):
            move_win(col, row, playfield)
    except AttributeError:
        pass


shuffler_args = sys.argv[1:]


if "arrange_all" in shuffler_args:
    subprocess.Popen([
        app_path + "/window_shuffler",
        "arrange_all",
        shuffler_args[1],
        shuffler_args[2]
    ])
elif shuffler_args[:2] == ["1", "1"]:
    toggle_max()
else:
    xmatrix, ymatrix, xpos, ypos = [int(shuffler_args[n]) for n in range(0, 4)]
    if len(shuffler_args) == 6:
        xsize, ysize = [int(shuffler_args[n]) for n in range(4, 6)]
        if xsize > xmatrix - xpos:
            xsize = xmatrix - xpos
        elif xsize < 1:
            xsize = 1
        if ysize > ymatrix - ypos:
            ysize = ymatrix - ypos
        elif ysize < 1:
            ysize = 1
    else:
        xsize, ysize = 1, 1

    # Wnck
    screendata = Wnck.Screen.get_default()
    screendata.force_update()
    curr_subject = screendata.get_active_window()
    xycoords = [xmatrix, ymatrix]
    move_window(xpos, ypos)
