"""
                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "{}"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright {yyyy} {name of copyright owner}

   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 os.path
import cv2
import numpy as np
import keras.backend as keras_backend
from keras.layers import Input
from keras.models import Model
import keras_frcnn.roi_helpers as roi_helpers
import keras_frcnn.config
import keras_frcnn.resnet as network
import core.sequence_type
import core.trained_system
import trials.object_detection.bounding_box_result as bbox_result
import systems.deep_learning.config_helpers as config_help


class KerasFRCNN(core.trained_system.TrainedVisionSystem):
    """
    A Vision system for testing a keras-based FRCNN that does bounding-box estimation
    Based on keras-frcnn, found here: https://github.com/yhenon/keras-frcnn.
    This file is derived from test_frcnn.py and train_frcnn.py in the above project.
    TODO: Can support VGG as well as Resnet50
    """

    def __init__(self, config, vision_system_trainer, num_rois=32,
                 training_image_source_ids=None, training_settings=None, id_=None):
        super().__init__(vision_system_trainer=vision_system_trainer,
                         training_image_source_ids=training_image_source_ids,
                         training_settings=training_image_source_ids, id_=id_)

        if not isinstance(config, keras_frcnn.config.Config):
            raise ValueError("Config parameter must be a keras_frcnn configuration produced during training."
                             " Train a model or unpickle an existing one.")

        # Config
        self._config = config
        self._config.num_rois = int(num_rois)
        self._bbox_threshold = 0.8      # Configurable, perhaps?

        # No data augmentation when testing
        self._use_horizontal_flips = self._config.use_horizontal_flips
        self._use_vertical_flips = self._config.use_vertical_flips
        self._rot_90 = self._config.rot_90
        self._config.use_horizontal_flips = False
        self._config.use_vertical_flips = False
        self._config.rot_90 = False

        # Trial state
        self._gt_bounding_boxes = None
        self._bounding_boxes = None
        self._model_rpn = None
        self._model_classifier_only = None
        self._sequence_type = None
        self._class_mapping = {}

    @property
    def num_regions_of_interest(self):
        return self._config.num_rois

    @num_regions_of_interest.setter
    def num_regions_of_interest(self, num_rois):
        if not self.is_trial_running():
            self._config.num_rois = int(num_rois)

    def is_trial_running(self):
        """
        Has the trial started.
        Don't change the config when the trial is running
        :return:
        """
        return self._bounding_boxes is not None

    @property
    def is_deterministic(self):
        """
        Is the visual system deterministic.
        :return: True, features are deterministic
        :rtype: bool
        """
        return True

    def is_image_source_appropriate(self, image_source):
        """
        Is the dataset appropriate for testing this vision system.
        Requirements are that we have ground-truth labels and that we can match back to the image ids.
        TODO: Copy information from the image, so we don't have to index back to it.
        :param image_source: The source for images that this system will potentially be run with.
        :return: True iff the particular dataset is appropriate for this vision system.
        :rtype: bool
        """
        return image_source.is_stored_in_database and image_source.is_labels_available

    def set_camera_intrinsics(self, camera_intrinsics):
        """
        Set the camera intrinsics. Maybe want to unwarp images before input or something.
        :param camera_intrinsics:
        :return:
        """
        pass

    def start_trial(self, sequence_type):
        """
        Start a trial for a feature detector
        :return: void
        """

        # TODO: Maybe need to set the recursion limit? Look for crashes if this is missing
        # self._old_recusion_limit = sys.getrecursionlimit()
        # if self._old_recursion_limit < 40000:
        #     sys.setrecursionlimit(40000)

        # Set up a mapping between integer ids and class names
        class_mapping = self._config.class_mapping
        if 'bg' not in class_mapping:
            class_mapping['bg'] = len(class_mapping)
        self._class_mapping = {v: k for k, v in class_mapping.items()}

        # Construct the network
        if keras_backend.image_dim_ordering() == 'th':
            input_shape_img = (3, None, None)
            input_shape_features = (1024, None, None)
        else:
            input_shape_img = (None, None, 3)
            input_shape_features = (None, None, 1024)

        img_input = Input(shape=input_shape_img)
        roi_input = Input(shape=(self._config.num_rois, 4))
        feature_map_input = Input(shape=input_shape_features)

        # define the base network (resnet here, can be VGG, Inception, etc)
        shared_layers = network.nn_base(img_input, trainable=True)

        # define the RPN, built on the base layers
        num_anchors = len(self._config.anchor_box_scales) * len(self._config.anchor_box_ratios)
        rpn_layers = network.rpn(shared_layers, num_anchors)

        classifier = network.classifier(feature_map_input, roi_input, self._config.num_rois,
                                        nb_classes=len(class_mapping), trainable=True)

        self._model_rpn = Model(img_input, rpn_layers)
        self._model_classifier_only = Model([feature_map_input, roi_input], classifier)

        model_classifier = Model([feature_map_input, roi_input], classifier)

        self._model_rpn.load_weights(self._config.model_path, by_name=True)
        model_classifier.load_weights(self._config.model_path, by_name=True)

        self._model_rpn.compile(optimizer='sgd', loss='mse')
        model_classifier.compile(optimizer='sgd', loss='mse')

        # Record the results
        self._sequence_type = core.sequence_type.ImageSequenceType(sequence_type)
        self._bounding_boxes = {}
        self._gt_bounding_boxes = {}

    def process_image(self, image, timestamp):
        """
        Process an image as part of the current run.
        :param image: An Image object
        :param timestamp: The timestamp or index of the image in this collection
        :return: void
        """
        if not self.is_trial_running():
            self.start_trial(core.sequence_type.ImageSequenceType.NON_SEQUENTIAL)

        # Convert the input image to be fed into the network
        formatted_image, aspect_ratio = format_img(image.data, self._config)
        if keras_backend.image_dim_ordering() == 'tf':
            formatted_image = np.transpose(formatted_image, (0, 2, 3, 1))

        # get the feature maps and output from the RPN (Region Proposal Network)
        [rpn_class, rpn_regr, shared_layers_output] = self._model_rpn.predict(formatted_image)

        # Convert region proposals to bounding boxes
        regions = roi_helpers.rpn_to_roi(rpn_class, rpn_regr, self._config, keras_backend.image_dim_ordering(),
                                        overlap_thresh=0.7)

        # convert from (x1,y1,x2,y2) to (x,y,w,h)
        regions[:, 2] -= regions[:, 0]
        regions[:, 3] -= regions[:, 1]

        # apply the spatial pyramid pooling to the proposed regions
        bboxes = {}
        probs = {}
        for jk in range(regions.shape[0] // self._config.num_rois + 1):  # // indicates integer division
            regions_of_interest = np.expand_dims(regions[self._config.num_rois * jk:
                                                        self._config.num_rois * (jk + 1), :], axis=0)
            if regions_of_interest.shape[1] == 0:
                break

            if jk == regions.shape[0] // self._config.num_rois:
                # pad regions
                curr_shape = regions_of_interest.shape
                target_shape = (curr_shape[0], self._config.num_rois, curr_shape[2])
                rois_padded = np.zeros(target_shape).astype(regions_of_interest.dtype)
                rois_padded[:, :curr_shape[1], :] = regions_of_interest
                rois_padded[0, curr_shape[1]:, :] = regions_of_interest[0, 0, :]
                regions_of_interest = rois_padded

            [prob_class, prob_regr] = self._model_classifier_only.predict([shared_layers_output, regions_of_interest])

            for ii in range(prob_class.shape[1]):

                # If our most likely class is less than our threshold, or is background
                if (np.max(prob_class[0, ii, :]) < self._bbox_threshold or
                        np.argmax(prob_class[0, ii, :]) == (prob_class.shape[2] - 1)):
                    continue

                cls_name = self._class_mapping[np.argmax(prob_class[0, ii, :])]
                if cls_name not in bboxes:
                    bboxes[cls_name] = []
                    probs[cls_name] = []

                (x, y, w, h) = regions_of_interest[0, ii, :]

                cls_num = np.argmax(prob_class[0, ii, :])
                try:
                    (tx, ty, tw, th) = prob_regr[0, ii, 4 * cls_num:4 * (cls_num + 1)]
                    tx /= self._config.classifier_regr_std[0]
                    ty /= self._config.classifier_regr_std[1]
                    tw /= self._config.classifier_regr_std[2]
                    th /= self._config.classifier_regr_std[3]
                    x, y, w, h = roi_helpers.apply_regr(x, y, w, h, tx, ty, tw, th)
                except:
                    pass
                bboxes[cls_name].append([self._config.rpn_stride * x, self._config.rpn_stride * y,
                                         self._config.rpn_stride * (x + w), self._config.rpn_stride * (y + h)])
                probs[cls_name].append(np.max(prob_class[0, ii, :]))

        # Aggregate the detected bounding boxes into results for this image
        detected_bboxes = []
        for key in bboxes.keys():
            bbox = np.array(bboxes[key])

            new_boxes, new_probs = roi_helpers.non_max_suppression_fast(bbox, np.array(probs[key]), overlap_thresh=0.5)
            for jk in range(new_boxes.shape[0]):
                x1, y1, x2, y2 = new_boxes[jk, :]
                real_x1, real_y1, real_x2, real_y2 = get_real_coordinates(aspect_ratio, x1, y1, x2, y2)
                detected_bboxes.append(bbox_result.BoundingBox(
                    class_names=(key,),
                    confidence=new_probs[jk],
                    x=real_x1,
                    y=real_y1,
                    width=real_x2 - real_x1,
                    height=real_y2 - real_y1
                ))

        self._bounding_boxes[image.identifier] = detected_bboxes
        self._gt_bounding_boxes[image.identifier] = (
            bbox_result.BoundingBox(class_names=obj.class_names,
                                    confidence=1,
                                    x=obj.bounding_box[0],
                                    y=obj.bounding_box[1],
                                    width=obj.bounding_box[2],
                                    height=obj.bounding_box[3])
            for obj in image.metadata.labelled_objects
        )

    def finish_trial(self):
        """
        End the current trial, returning a trial result.
        Return none if no trial is started.
        :return:
        :rtype TrialResult:
        """
        # TODO: Maybe need to set the recursion limit?
        # sys.setrecursionlimit(self._old_recursion_limit)
        self._model_rpn = None
        self._model_classifier_only = None
        self._class_mapping = {}
        result = bbox_result.BoundingBoxResult(
            system_id=self.identifier,
            bounding_boxes=self._bounding_boxes,
            ground_truth_bounding_boxes=self._gt_bounding_boxes,
            sequence_type=self._sequence_type,
            system_settings=config_help.serialize_config(self._config)
        )
        self._bounding_boxes = None
        self._gt_bounding_boxes = None
        return result

    def validate(self):
        """
        Check that the system is valid.
        Checks that the weights file exists.
        :return: True iff the weights hdf5 file exists
        """
        return os.path.isfile(self._config.model_path)

    def serialize(self):
        """
        Serialize the entity to a dict format, that can be saved to the database
        :return: a dictionary representation of the entity, that can be saved to MongoDB
        """
        serialized = super().serialize()
        # restore original settings for serialization
        self._config.use_horizontal_flips = self._use_horizontal_flips
        self._config.use_vertical_flips = self._use_vertical_flips
        self._config.rot_90 = self._rot_90
        serialized['config'] = config_help.serialize_config(self._config)
        self._config.use_horizontal_flips = False
        self._config.use_vertical_flips = False
        self._config.rot_90 = False
        return serialized

    @classmethod
    def deserialize(cls, serialized_representation, db_client, **kwargs):
        """
        Deserialize an Entity as retrieved from the database
        Also accepts keyword arguments that are passed directly to the entity constructor,
        so that we can have required parameters to the initialization
        :param serialized_representation: dict
        :param db_client: DatabaseClient for deserializing child objects
        :return: An instance of the entity class, constructed from the serialized representation
        """
        if 'config' in serialized_representation:
            kwargs['config'] = config_help.deserialize_config(serialized_representation['config'])
        return super().deserialize(serialized_representation, db_client, **kwargs)


def format_img_size(img, config):
    """ formats the image size based on config """
    img_min_side = float(config.im_size)
    (height, width, _) = img.shape

    if width <= height:
        ratio = img_min_side / width
        new_height = int(ratio * height)
        new_width = int(img_min_side)
    else:
        ratio = img_min_side / height
        new_width = int(ratio * width)
        new_height = int(img_min_side)
    img = cv2.resize(img, (new_width, new_height), interpolation=cv2.INTER_CUBIC)
    return img, ratio


def format_img_channels(img, config):
    """ formats the image channels based on config """
    img = np.array(img, copy=True, dtype=np.float32)
    img[:, :, 0] -= config.img_channel_mean[0]
    img[:, :, 1] -= config.img_channel_mean[1]
    img[:, :, 2] -= config.img_channel_mean[2]
    img /= config.img_scaling_factor
    img = np.transpose(img, (2, 0, 1))
    img = np.expand_dims(img, axis=0)
    return img


def format_img(img, config):
    """ formats an image for model prediction based on config """
    img, ratio = format_img_size(img, config)
    img = format_img_channels(img, config)
    return img, ratio


def get_real_coordinates(ratio, x1, y1, x2, y2):
    """
    Method to transform the coordinates of the bounding box to its original size
    :param ratio:
    :param x1:
    :param y1:
    :param x2:
    :param y2:
    :return:
    """
    real_x1 = int(round(x1 // ratio))
    real_y1 = int(round(y1 // ratio))
    real_x2 = int(round(x2 // ratio))
    real_y2 = int(round(y2 // ratio))
    return real_x1, real_y1, real_x2, real_y2
