#  Copyright 2017 Carlos Pascual-Izarra <cpascual@users.sourceforge.net>
#
#  This file is part of PeakEvo.
#
#  PeakEvo 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
#  (at your option) any later version.
#
#  PeakEvo 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 Foobar.  If not, see <http://www.gnu.org/licenses/>.


import time

import numpy

# from mock import MagicMock


class DummySpectrometer(object):
    """A SeaBreeze Spectrometer class with some API candy"""

    def __init__(self, dev=None, integ_time=1000):
        self.integration_time_micros_limits = (1000, 1_000_000)
        self.integration_time = integ_time
        self._w = numpy.linspace(200, 1200, 2048, dtype="float64")
        self.dx = 5
        self.x0 = 500

    def wavelengths(self):
        return self._w

    def intensities(self, **kwargs):
        time.sleep(self.integration_time / 1e6)
        x = self._w.astype("float64")
        ret = 0
        # for c in (1, 0.3, 0.2):
        #     x0 = numpy.random.randint(400, 800)
        #     s = numpy.random.randint(10, 200)
        #     ret += gaussian(x, x0, s)

        ret += 2 * gaussian(x, self.x0, numpy.random.randint(100, 200))
        ret += 0.3 * gaussian(
            x, numpy.random.randint(50, 70), numpy.random.randint(50, 70)
        )
        ret += 0.3 * gaussian(
            x, numpy.random.randint(800, 1000), numpy.random.randint(50, 70)
        )
        self.x0 += self.dx
        if abs(self.x0 - 500) > 100:
            self.dx *= -1

        ret *= self.integration_time / 10 / ret.max()
        ret += numpy.abs(numpy.random.normal(0, 200, ret.size))
        ret = numpy.where(ret > 65535, 65535, ret)
        ret = ret.astype("float64")
        return ret

    def capture(self):
        return self.wavelengths(), self.intensities()


def gaussian(x, x0, s):
    return numpy.exp(-0.5 * ((x - x0) / float(s)) ** 2) / (s * numpy.sqrt(2 * numpy.pi))


if __name__ == "__main__":
    s = DummySpectrometer()
    print(s.capture())
