<?php

/*
 * Soluble Japha
 *
 * @link      https://github.com/belgattitude/soluble-japha
 * @copyright Copyright (c) 2013-2020 Vanvelthem Sébastien
 * @license   MIT License https://github.com/belgattitude/soluble-japha/blob/master/LICENSE.md
 */

namespace SolubleTest\Japha\ThirdParty;

use Soluble\Japha\Bridge\Adapter;
use PHPUnit\Framework\TestCase;

/**
 * Generated by PHPUnit_SkeletonGenerator on 2014-11-04 at 16:47:42.
 */
class GsonTest extends TestCase
{
    /**
     * @var string
     */
    protected $servlet_address;

    /**
     * @var Adapter
     */
    protected $adapter;

    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     */
    protected function setUp(): void
    {
        if (!$this->isGSONTestsEnabled()) {
            $this->markTestSkipped(
                'Skipping GSON tests, enable option in phpunit.xml'
            );
        }

        \SolubleTestFactories::startJavaBridgeServer();

        $this->servlet_address = \SolubleTestFactories::getJavaBridgeServerAddress();

        $this->adapter = new Adapter([
            'driver' => 'Pjb62',
            'servlet_address' => $this->servlet_address,
        ]);
    }

    /**
     * @see https://github.com/google/gson
     */
    public function testJavaSimpleJsonSerialization()
    {
        $ba = $this->adapter;

        $gson = $ba->java('com.google.gson.Gson');
        $jsonString = $gson->toJson($ba->java('java.lang.String', 'Héllo'));

        self::assertEquals('"Héllo"', (string) $jsonString);
    }

    public function testObjectJsonSerialization()
    {
        $ba = $this->adapter;
        $gson = $ba->java('com.google.gson.Gson');

        $simpleDateFormat = $ba->java('java.text.SimpleDateFormat', 'yyyy-MM-dd');

        $hashMap = $ba->java('java.util.HashMap', [
            'integer' => 1,
            'phpstring' => 'PHP Héllo',
            'javastring' => $ba->java('java.lang.String', 'Java Héllo'),
            'javadate' => $simpleDateFormat->parse('2017-05-20')
        ]);

        $jsonString = (string) $gson->toJson($hashMap);
        // Will produce:
        //   {
        //     "javastring":"Java Héllo",
        //     "javadate":"May 20, 2017 12:00:00 AM",
        //     "phpstring":"PHP Héllo",
        //     "integer":1
        //   }

        self::assertJson($jsonString);
        $decoded = json_decode($jsonString);
        self::assertEquals('Java Héllo', $decoded->javastring);
    }

    protected function isGSONTestsEnabled()
    {
        return isset($_SERVER['JAPHA_ENABLE_GSON_TESTS']) &&
            $_SERVER['JAPHA_ENABLE_GSON_TESTS'] == true;
    }
}
